1、导入pom依赖
<!--xls(03)-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!--xlsx(07)-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<!--日期格式化工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.6</version>
</dependency>
<!--test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
2、创建Excel文件并写入
@Test
public void TestWrite() throws Exception {
//1、创建一个工作簿
//如果使用07版本的xlsx只要将对象修改为XSSFWorkbook即可。
Workbook workbook = new HSSFWorkbook();
//2、创建一个工作表
Sheet sheet = workbook.createSheet("淡墨工作簿");
//3、创建一个行(1,1)
Row row1 = sheet.createRow(0);
//4、创建一个单元格
Cell cell11 = row1.createCell(0);
cell11.setCellValue("今日工作内容");
//(1,2)
Cell cell12 = row1.createCell(1);
cell12.setCellValue("6666");
//第二行
Row row2 = sheet.createRow(1);
//(2,1)
Cell cell21 = row2.createCell(0);
cell21.setCellValue("统计时间");
//(2,2)
Cell cell22 = row2.createCell(1);
//或当当前日期时间
String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
cell22.setCellValue(time);
//生成一张表(IO流)03版本就是使用xls结尾,07版本就是使用xlsx结尾!
FileOutputStream fileOutputStream = new FileOutputStream("淡墨日记.xls");
//写入流
workbook.write(fileOutputStream);
//关闭流
fileOutputStream.close();
System.out.println("淡墨日记生成完毕");
}
如果是大数据的导出则使用SXSSFWorkbook对象:
@Test
public void testWrite07S() throws Exception {
//1、创建一个工作簿
Workbook workbook = new SXSSFWorkbook();
//2、创建一个工作表
Sheet sheet = workbook.createSheet("淡墨工作簿");
//写入数据
for (int rowNum = 0; rowNum < 100000; rowNum++) {
Row row = sheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 20; cellNum++) {
Cell cell = row.createCell(cellNum);
cell.setCellValue(cellNum);
}
}
//生成一张表(IO流)03版本就是使用xlsx结尾!
FileOutputStream fileOutputStream = new FileOutputStream("淡墨日记.xlsx");
//写入流
workbook.write(fileOutputStream);
//关闭流
fileOutputStream.close();
//清除临时文件
((SXSSFWorkbook) workbook).dispose();
System.out.println("淡墨日记生成完毕");
}