今天给产品原型增加导出excel的功能,使用POI,方法如下:
1. 引用POI库(pom.xml)
<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
2. 代码:
生成word文件到指定目录,并返回文件名。
说明,本例并不是直接新建文档,而是从一个文档模板读取,并在它基础上添加行。如果对格式有要求的话,在代码中处理格式那就太折腾了,不如在模板中先把部分格式设置好,提高效率。
本例使用XWPF(.docx格式),HWPF针对 .doc格式,但是只能读不能写,因此不考虑。
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
//...
String[][] data = ...//初始化数据(m行 * nlie)的表格
String fileName = "XXX.docx";
String exportPath = "D:\\export"
File file = new File(exportPath + "\\a_word_temp.docx"); //读取模板,比较方便一点
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
XWPFDocument document = new XWPFDocument(fis);
XWPFTable table = document.getTables().get(0);
//data填充
int colNum = data[0].length; //列的数量
for(String[] strs: data) {
XWPFTableRow row = table.createRow();
for(int i = 0; i < colNum; i++) {
row.getCell(i).setText(strs[i]);
}
}
FileOutputStream fos = new FileOutputStream(exportPath+"\\"+fileName);
document.write(fos);
fos.close();
document.close();
return "ok" + fileName;
3. 前端调用下载:
//...
window.open(url+"/file/download/export/" + fileName);
文档模板:
导出效果: