public class TestExcel {
static Log log = LogFactory.getLog(TestExcel.class);
private final static int httpPort = 8087;
@Autowired
PhoneMatchCodeService phoneMatchCodeService;
// 获取Excel文档的路径
public static String filePath = "E://phoneMatchCode//phoneMatchCode.xlsx";
private String saveData() {
try {
// 创建对Excel工作簿文件的引用
Workbook wookbook = null;
// OPCPackage pkg = OPCPackage.open(path);
wookbook = new XSSFWorkbook(new FileInputStream(filePath));
// HSSFWorkbook wookbook = new HSSFWorkbook(new
// FileInputStream(filePath));
// 在Excel文档中,第一张工作表的缺省索引是0
// 其语句为: HSSFSheet sheet = workbook.getSheetAt(0);
Sheet sheet = wookbook.getSheet("Sheet1");
// HSSFSheet sheet = wookbook.getSheet("Sheet1");
// 获取到Excel文件中的所有行数
int rows = sheet.getPhysicalNumberOfRows();
// 遍历行
PhoneMatchCode phoneMatchCode = new PhoneMatchCode();
for (int i = 1; i < rows; i++) {
// 读取左上端单元格
Row row = sheet.getRow(i);
// 行不为空
if (row != null) {
// 获取到Excel文件中的所有的列
int cells = row.getPhysicalNumberOfCells();
String value = ""; // 遍历列
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
phoneMatchCode.setCode(row.getCell(0).getStringCellValue());
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
phoneMatchCode.setMatchCode(row.getCell(1).getStringCellValue());
row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
phoneMatchCode.setProvince(row.getCell(2).getStringCellValue());
row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
phoneMatchCode.setCity(row.getCell(3).getStringCellValue());
System.out.println(phoneMatchCode.getCity());
phoneMatchCodeService.add(phoneMatchCode);
}
}
return "ok";
} catch (Exception e) {
log.error("excell 解析失败", e);
return "error";
}
}
}