java数据导出到Excel
最近遇到的需求,需要把数据处理好后导成一个个的excel表,网上查阅一番后,亲测可用的用法。
1.pom文件
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
对excel对象的操作,常用的API的由import org.apache.poi.hssf.usermodel.*;
包下的HSSF开头的来完成。
2.使用API
2.1相当于获得excel对象
HSSFWorkbook workbook = ExcelUtils.getExcel();
public static HSSFWorkbook getExcel() {
return new HSSFWorkbook();
}
2.2创建excel的sheet
HSSFSheet sheet = workbook.createSheet("sheet");
相当于这个
2.3创建表格的菜单栏
HSSFRow row0 = ExcelUtils.createRow(sheet, 0);
public static HSSFRow createRow(HSSFSheet sheet, int row) {
return sheet.createRow(row);
}
2.4给菜单栏设置名称
String[] title = {"日期(yyyy/mm/dd)", "工作量", "工作类型", "内容"};
row0 = ExcelUtils.setTitle(row0, title);
public static HSSFRow setTitle(HSSFRow row, String[] title) {
for (int i = 0; i < title.length; i++) {
row.createCell(i).setCellValue(title[i]);
}
return row;
}
2.5创建数据行
HSSFRow row = ExcelUtils.createRow(sheet, 1);
2.6给数据行存入数据
row.createCell(0).setCellValue(“2020/04/30”);
row.createCell(1).setCellValue(“8小时”);
row.createCell(2).setCellValue(“体力活”);
row.createCell(3).setCellValue(“搬砖”);
2.7输出到文件
workbook.write(new File("C:\\今日工作总结.xls"));
3看效果
4可能会遇到的问题
当需要转出数据的属性值太多时,即需要导出的excel的列太多,超过256列,hssf包下的HSSF*对象
可能会报错,不允许超过256列。
因此需要poi-ooxml下的poi.xssf的XSSF*
对象,XSSFCell
最大支持16384列,并且数据量大时,性能要远大于HSSF*。
备注:完整代码
ExcelUtils
public class ExcelUtils {
public static HSSFRow setTitle(HSSFRow row, String[] title) {
for (int i = 0; i < title.length; i++) {
row.createCell(i).setCellValue(title[i]);
}
return row;
}
public static HSSFRow createRow(HSSFSheet sheet, int row) {
return sheet.createRow(row);
}
public static HSSFWorkbook getExcel() {
return new HSSFWorkbook();
}
}
调用
public void test() throws IOException {
HSSFWorkbook workbook = ExcelUtils.getExcel();
HSSFSheet sheet = workbook.createSheet("sheet");
HSSFRow row0 = ExcelUtils.createRow(sheet, 0);
String[] title = {"日期(yyyy/mm/dd)", "工作量", "工作类型", "内容"};
row0 = ExcelUtils.setTitle(row0, title);
HSSFRow row = ExcelUtils.createRow(sheet, 1);
row.createCell(0).setCellValue(“2020/04/30”);
row.createCell(1).setCellValue(“8小时”);
row.createCell(2).setCellValue(“体力活”);
row.createCell(3).setCellValue(“搬砖”);
workbook.write(new File("C:\\今日工作总结.xls"));
}