1.导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.1</version>
</dependency>
2.代码实现
package com.example.exceldemo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class EasyExcelTest {
public static void main(String[] args) throws Exception {
InputStream fis = null;
OutputStream outputStream= null;
Workbook wb = null;
try {
String fileName = "测试单位"+ UUID.randomUUID() + ".xlsx";
String filePath = "D:\\report\\"+fileName;
List<ExcelVo> list = new ArrayList<>();
list.add(new ExcelVo(1,"1221","黄山"));
list.add(new ExcelVo(2,"3333","河水"));
list.add(new ExcelVo(3,"6666","青石"));
fis = new ClassPathResource("templates/report_template.xlsx").getInputStream();
File file=new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
outputStream = new FileOutputStream(file);
wb = new XSSFWorkbook(fis);
Sheet sheet = wb.getSheetAt(0);
CellStyle styles[] = new CellStyle[row.getLastCellNum()];
Row row = sheet.getRow(1);
CellStyle styles[] = new CellStyle[row.getLastCellNum()];
Cell cell = null;
for (int i = 0; i < row.getLastCellNum(); i++) {
cell = row.getCell(i);
styles[i] = cell.getCellStyle();
}
int rowIndex=1;
for (ExcelVo vo2:list) {
row= sheet.createRow(rowIndex++);
int i=0;
cell = row.createCell(i++);
cell.setCellStyle(styles[0]);
cell.setCellValue(vo2.getId());
cell = row.createCell(i++);
cell.setCellStyle(styles[0]);
cell.setCellValue(vo2.getCode());
cell = row.createCell(i);
cell.setCellStyle(styles[0]);
cell.setCellValue(vo2.getName());
}
for (ExcelVo t:list) {
row = sheet.createRow(rowIndex++);
Field[] fields=t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field=fields[i];
field.setAccessible(true);
Object val = field.get(t);
if (val==null)val="";
cell = row.createCell(i);
cell.setCellStyle(styles[0]);
cell.setCellValue(val.toString());
}
}
wb.write(outputStream);
} catch (Exception e) {
throw new Exception(e);
} finally {
fis.close();
wb.close();
outputStream.close();
}
}
}
3.模板
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3e33b58b40ccd2bcaed1c420d99749ad.png)
参考:https://blog.csdn.net/weixin_45742032/article/details/119593288?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-1-119593288-blog-86538258.235%5Ev38%5Epc_relevant_anti_t3_base&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-1-119593288-blog-86538258.235%5Ev38%5Epc_relevant_anti_t3_base&utm_relevant_index=2