导入依赖
org.apache.poi
poi
RELEASE
实体类entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExcelTXT {
private Integer id;
private String name;
private String area;
private String age;
private String sex;
}
测试类
@Test
public void Test1() {
System.out.println(1);
List list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new ExcelTXT(1, "2", "3", "4", "5"));
}
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream("D:\Work\Project\2021-9 先打后补v2.1-Win(1)\新建 Microsoft Excel 工作表.xls");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
downLoadToExcel(outputStream,list);
}
public static int downLoadToExcel(OutputStream outputStream, List paimaiMoneyVOList) {
//文档对象
HSSFWorkbook wb = new HSSFWorkbook();
int rowNum = 0;
Sheet sheet = wb.createSheet("excel的标题");
Row row0 = sheet.createRow(rowNum++);
//因为场景不同,titil不同,可以在外面写成数组当参数传进来
row0.createCell(0).setCellValue("序号n" );
row0.createCell(1).setCellValue("姓名n" );
row0.createCell(2).setCellValue("地址n");
row0.createCell(3).setCellValue("年龄n");
row0.createCell(4).setCellValue("性别n");
if (paimaiMoneyVOList != null && paimaiMoneyVOList.size() > 0) {
for (ExcelTXT paimaiMoneyVO : paimaiMoneyVOList) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(paimaiMoneyVO.getId());
row.createCell(1).setCellValue(paimaiMoneyVO.getName());
row.createCell(2).setCellValue(paimaiMoneyVO.getArea());
row.createCell(3).setCellValue(paimaiMoneyVO.getAge());
row.createCell(4).setCellValue(paimaiMoneyVO.getSex());
}
}
try {
wb.write(outputStream);
// LOGGER.info("表数据写入到excel表成功,一共写入了" + (rowNum - 1) + "条数据");
outputStream.close();
} catch (IOException e) {
// LOGGER.error("流关闭异常!", e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
// LOGGER.error("流关闭异常!", e);
}
}
}
return rowNum - 1;
}