1、需要引入的maven依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
2、代码示例
public class UpdateExcelUtil {
public static void updateExcelUtil(List<Map> mapList) throws Exception {
String path = new File("").getCanonicalPath();
File file = new File(path+"/src/test/resources/电子卡密批量导入模板.xlsx");
FileInputStream fileInputStream = new FileInputStream(file);
XSSFWorkbook sheets = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = sheets.getSheetAt(0);
//获取最后一行
int lastRowNum = sheet.getLastRowNum();
//删除数据
if(lastRowNum>1){
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
sheet.removeRow(row);
}}
for (int rowId = 0; rowId < mapList.size(); rowId++) {
Map<String, String> map = mapList.get(rowId);
XSSFRow newRow = sheet.createRow(rowId + 1);
String code = map.get("商品编码");
String cardid = map.get("卡号");
String psd = map.get("密码");
XSSFCell cell0 = newRow.createCell(0);
XSSFCell cell1 = newRow.createCell(1);
XSSFCell cell2 = newRow.createCell(2);
cell0.setCellValue(code);
cell1.setCellValue(cardid);
cell2.setCellValue(psd);
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
sheets.write(fileOutputStream);
fileInputStream.close();
fileOutputStream.close();
}