文章目录
一.写入表格操作二.读表操作
前提:使用 java poi 的包
一.写入表格操作
synchronized public static void writeExcel(String excelName
, List
<String
[]> excelData
) throws Exception
{
String absoluteExcelPath
= new File("").getCanonicalPath() + "/src/test/resources/" + excelName
;
File excelFile
= new File(absoluteExcelPath
);
Workbook workbook
= WorkbookFactory
.create(excelFile
);
Sheet sheet
= workbook
.getSheetAt(0);
for(int rowNum
= sheet
.getLastRowNum() + 1, i
= 0; i
< data
.size(); rowNum
++, i
++) {
Row row
= sheet
.getRow(rowNum
);
String
[] rowData
= excelData
.get(i
);
for(int columnNum
= row
.getLastCellNum() + 1, j
= 0; j
< rowData
.length
; columnNum
++, j
++){
row
.createCell(columnNum
).setCellValue(rowData
[j
]);
}
}
FileOutputStream out
=new FileOutputStream(absoluteExcelPath
);
out
.flush();
workbook
.write(out
);
out
.close();
}
二.读表操作
synchronized public static List
<String
[]> readExcel(String excelName
) throws Exception
{
String absoluteExcelPath
= new File("").getCanonicalPath() + "/src/test/resources/" + excelName
;
File excelFile
= new File(absoluteExcelPath
);
Workbook workbook
= WorkbookFactory
.create(excelFile
);
Sheet sheet
= workbook
.getSheetAt(0);
List
<String
[]> dataList
= new ArrayList<>();
for(int rowNum
= 0, i
= 0; i
<= sheet
.getLastRowNum(); rowNum
++, i
++) {
Row row
= sheet
.getRow(rowNum
);
String
[] rowString
= new String[row
.getLastCellNum() + 1];
for(int columnNum
= 0, j
= 0; j
< row
.getLastCellNum(); columnNum
++, j
++){
Cell cell
= row
.getCell(columnNum
);
cell
.setCellType(CellType
.STRING
);
rowString
[j
] = new DataFormatter().formatCellValue(cell
);
}
dataList
.add(rowString
);
}
return dataList
;
}
转载请注明原文地址: https://mac.8miu.com/read-493962.html