在pom.xml中增加jar包支持
<!--excel数据表格导出 statrt -->
<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>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<!-- 获取数据转换的时候用到 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<!--excel数据表格导出 end -->
生成Excel表格数据工具类
public class ExcelBigUtil {
public static void main(String[] args) {
List<String[]> arrayList = new ArrayList<>();
String[] arry1 = {"小明1", "小明2", "小明3", "小明4", "小明5", "小明6", "小明7", "小明8"};
String[] arry2 = {"第二条数据1", "第二条数据2", "第二条数据3", "第二条数据4", "第二条数据5", "第二条数据6", "第二条数据7", "第二条数据8"};
String[] arry3 = {"第三条数据1", "第三条数据2", "第三条数据3", "第三条数据4", "第三条数据5", "第三条数据6", "第三条数据7", "第三条数据8"};
String[] arry4 = {"第四条数据1", "第四条数据2", "第四条数据3", "第四条数据4", "第四条数据5", "第四条数据6", "第四条数据7", "第四条数据8"};
String[] arry5 = {"第五条数据1", "第五条数据2", "第五条数据3", "第五条数据4", "第五条数据5", "第五条数据6", "第五条数据7", "第五条数据8"};
for (int i = 0; i < 200000; i++) { //100万数据17秒生成
arrayList.add(arry1);
arrayList.add(arry2);
arrayList.add(arry3);
arrayList.add(arry4);
arrayList.add(arry5);
}
System.out.println("=======size:" + arrayList.size());
String fieldArray[] = {"标题1", "标题2", "标题3", "标题4", "标题5", "标题6", "标题7", "标题8"};
try {
System.out.println("----start------" + DateUtil.getNowDate());//Mon Apr 27 16:32:10 CST 2020
//在D盘建立Excel表格:excel2010.xlsx
exportBigExcel(fieldArray, arrayList, "D:\\excel2010.xlsx");//Mon Apr 27 16:32:27 CST 2020
System.out.println("----end------" + DateUtil.getNowDate());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 导出大量数据到EXCEL表格
* 支持:(Excel 2007)
* @param fieldArray 表格头标题字段
* @param listArray 表格数据数组
* @param filePath excel文件的路径
* @throws IOException
*/
public static void exportBigExcel(String[] fieldArray, List<String[]> listArray, String filePath) throws IOException, InvalidFormatException {
XSSFWorkbook workbook1 = new XSSFWorkbook(new FileInputStream(filePath));
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(workbook1, 100);
Sheet first = sxssfWorkbook.getSheetAt(0);
//创建第一行的值
Row row = first.createRow(0);
for (int i = 0; i < fieldArray.length; i++) {
row.createCell(i).setCellValue(fieldArray[i]);
}
//从数据库取数据填充到Excel
for (int i = 1; i < listArray.size() + 1; i++) {//从第二行开始计算数据
String[] rowArray = listArray.get(i - 1);
Row rowTemp = first.createRow(i);
for (int j = 0; j < fieldArray.length; j++) {
rowTemp.createCell(j).setCellValue(rowArray[j]);
}
}
FileOutputStream out = new FileOutputStream(filePath);
sxssfWorkbook.write(out);
out.close();
}
}
来源:oschina
链接:https://my.oschina.net/u/3204029/blog/4257219