1.加入poi的依賴
2.demo
public JsonResult test(String filePath){
try {
filePath = "C:\\Users\\Administrator\\Desktop\\1.xlsx";
FileInputStream fs = new FileInputStream(filePath);
XSSFWorkbook hssfWorkbook =new XSSFWorkbook(fs);
XSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
// 向xls文件中寫數(shù)據(jù)
FileOutputStream out = new FileOutputStream(filePath);
// 獲取到最后一行
int physicalNumberOfRows = sheetAt.getPhysicalNumberOfRows();
for (int i = 0; i < physicalNumberOfRows; i++) {
// 獲取第i行(excel中的行默認(rèn)從0開始,所以這就是為什么,一個(gè)excel必須有字段列頭),即,字段列頭,便于賦值
XSSFRow row = sheetAt.getRow(i);
//獲取第一列數(shù)據(jù)
String content1= getCellValue(row.getCell(1));
row.createCell(21).setCellValue(content1+1); // 設(shè)置第二個(gè)(從0開始)單元格的數(shù)據(jù)
row.createCell(22).setCellValue(content1+2); // 設(shè)置第二個(gè)(從0開始)單元格的數(shù)據(jù)
}
out.flush();
hssfWorkbook.write(out);
out.close();
return new JsonResult(true, "excel success!");
} catch (Exception e) {
log.error("向excel中寫入數(shù)據(jù)時(shí)發(fā)生IO異常,異常如下:{}",e);
return new JsonResult(false, "excel fail message:"+e.getMessage());
}
}
private static String getCellValue(Cell cell) {
if (cell == null) return null;
cell.setCellType(CellType.STRING);
return cell.getStringCellValue();
}