java 导出Word(POI)

今天给产品原型增加导出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);

文档模板:

导出效果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鹰信息技术服务部

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值