poi导出word文档,doc和docx
maven
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>3.1.0</version>
</dependency> 判断单双页导出docx文档
/**
* 导出出租房屋
* @param request
* @return
*/
@RequestMapping(value = "exportRentalhouse",produces = {"application/json;chatset=utf-8"},method = RequestMethod.GET)
@ApiOperation(value = "导出出租房屋",notes = "导出出租房屋")
public AjaxResult exportRentalhouse(HttpServletRequest request, @RequestParam Map<String,Object> map,HttpServletResponse response) throws Exception {
try {
InputStream is = new FileInputStream(ResourceUtils.getFile("classpath:static/doc/rentahouse.docx"));
// InputStream is = new FileInputStream("E:\\desktop\\doc\\rentahouse.docx");
XWPFDocument doc = new XWPFDocument(is);
List<XWPFTable> tables = doc.getTables();
FileOutputStream outStream = null;
OutputStream os = response.getOutputStream();
String fileName = "出租房屋"+getTime();
response.setContentType("application/octet-stream; charset=utf-8");//导出word格式
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1")+".docx");
Map<String,Object> mm1 = new HashMap<String,Object>();
Map<String,Object> mm2 = new HashMap<String,Object>();
List<Map<String,Object>> listmap = new ArrayList<>();
mm1.put("rentaltleid","a5ba1e17ec6647eda347becad01aa3c3");
mm2.put("rentaltleid","9f61b54c5a2c4f9482a218183f5824de");
listmap.add(mm1);
listmap.add(mm2);
if(listmap.size() > 1){
OutputStream ot = new FileOutputStream(ResourceUtils.getFile("classpath:static/doc/temp.docx"));
for (int i = 1;i < listmap.size();i++) {
doc.createTable();
CTTbl ab = CTTbl.Factory.newInstance();
ab.set(doc.getTables().get(0).getCTTbl());
IBody iBody = doc.getTables().get(0).getBody();
XWPFTable newTable = new XWPFTable(ab, iBody);
doc.setTable(1,newTable);
}
doc.write(ot);
doc.close();
is.close();
InputStream is2 = new FileInputStream(ResourceUtils.getFile("classpath:static/doc/temp.docx"));
XWPFDocument doc2 = new XWPFDocument(is2);
List<XWPFTable> tables2 = doc2.getTables();
for (int i = 0;i < listmap.size();i++) {
List<Map<String,Object>> lm = appBusRentalhouseService.findRentalhouseContentList(listmap.get(i));
tables2.get(i).getRows().get(2).getTableCells().get(1).setText((String)lm.get(0).get("numberplate"));
tables2.get(i).getRows().get(2).getTableCells().get(3).setText((String)lm.get(0).get("lesseename"));
tables2.get(i).getRows().get(2).getTableCells().get(5).setText((String)lm.get(0).get("lesseephone"));
tables2.get(i).getRows().get(3).getTableCells().get(1).setText((String)lm.get(0).get("idcard"));
tables2.get(i).getRows().get(4).getTableCells().get(1).setText((String)lm.get(0).get("address"));
tables2.get(i).getRows().get(5).getTableCells().get(1).setText((String)lm.get(0).get("workunit"));
tables2.get(i).getRows().get(6).getTableCells().get(1).setText((String)lm.get(0).get("number"));
tables2.get(i).getRows().get(7).getTableCells().get(1).setText((String)lm.get(0).get("startdate"));
tables2.get(i).getRows().get(7).getTableCells().get(3).setText((String)lm.get(0).get("enddate"));
tables2.get(i).getRows().get(8).getTableCells().get(1).setText((String)lm.get(0).get("rent"));
tables2.get(i).getRows().get(8).getTableCells().get(3).setText((String)lm.get(0).get("waterrent"));
tables2.get(i).getRows().get(9).getTableCells().get(1).setText((String)lm.get(0).get("electriccharge"));
tables2.get(i).getRows().get(10).getTableCells().get(1).setText((String)lm.get(0).get("otherfees"));
tables2.get(i).getRows().get(12).getTableCells().get(0).setText((String)lm.get(0).get("detailedlist"));
tables2.get(i).getRows().get(31).getTableCells().get(4).setText((String)lm.get(0).get("writetime"));
tables2.get(i).getRows().get(31).getTableCells().get(1).setText((String)lm.get(0).get("title"));
tables2.get(i).getRows().get(31).getTableCells().get(4).setText((String)lm.get(0).get("eventtime"));
}
doc2.write(os);
doc2.close();
is2.close();
os.close();
}else{
List<Map<String,Object>> lm = appBusRentalhouseService.findRentalhouseContentList(listmap.get(0));
tables.get(0).getRows().get(2).getTableCells().get(1).setText((String)lm.get(0).get("numberplate"));
tables.get(0).getRows().get(2).getTableCells().get(3).setText((String)lm.get(0).get("lesseename"));
tables.get(0).getRows().get(2).getTableCells().get(5).setText((String)lm.get(0).get("lesseephone"));
tables.get(0).getRows().get(3).getTableCells().get(1).setText((String)lm.get(0).get("idcard"));
tables.get(0).getRows().get(4).getTableCells().get(1).setText((String)lm.get(0).get("address"));
tables.get(0).getRows().get(5).getTableCells().get(1).setText((String)lm.get(0).get("workunit"));
tables.get(0).getRows().get(6).getTableCells().get(1).setText((String)lm.get(0).get("number"));
tables.get(0).getRows().get(7).getTableCells().get(1).setText((String)lm.get(0).get("startdate"));
tables.get(0).getRows().get(7).getTableCells().get(3).setText((String)lm.get(0).get("enddate"));
tables.get(0).getRows().get(8).getTableCells().get(1).setText((String)lm.get(0).get("rent"));
tables.get(0).getRows().get(8).getTableCells().get(3).setText((String)lm.get(0).get("waterrent"));
tables.get(0).getRows().get(9).getTableCells().get(1).setText((String)lm.get(0).get("electriccharge"));
tables.get(0).getRows().get(10).getTableCells().get(1).setText((String)lm.get(0).get("otherfees"));
tables.get(0).getRows().get(12).getTableCells().get(0).setText((String)lm.get(0).get("detailedlist"));
tables.get(0).getRows().get(31).getTableCells().get(4).setText((String)lm.get(0).get("writetime"));
tables.get(0).getRows().get(31).getTableCells().get(1).setText((String)lm.get(0).get("title"));
tables.get(0).getRows().get(31).getTableCells().get(4).setText((String)lm.get(0).get("eventtime"));
doc.write(os);
doc.close();
is.close();
os.close();
}
return success(AjaxResult.Type.SUCCESS, "导出成功!", null);
} catch (Exception e) {
e.printStackTrace();
return error(AjaxResult.Type.ERROR,"导出失败",null);
}
} doc文档读取
public static void getDoc(String path) throws Exception {
Map<String,Object> map = new HashMap<String, Object>();
Map<String,Object> map = new HashMap<String, Object>();
try{
FileInputStream in = new FileInputStream(path);//载入文档
POIFSFileSystem pfs = new POIFSFileSystem(in);
HWPFDocument hwpf = new HWPFDocument(pfs);
Range range = hwpf.getRange();//得到文档的读取范围
TableIterator it = new TableIterator(range);
while (it.hasNext()) {
Table tables = (Table) it.next();
// for (int i = 0; i < tables.numRows(); i++) {
// TableRow tr = tables.getRow(i);
// for (int j = 0; j < tr.numCells(); j++) {
// TableCell td = tr.getCell(j);
// for(int k=0;k<td.numParagraphs();k++){
// System.out.println("-"+i+"-"+j+"-"+k+"="+td.getParagraph(k).text());
// Paragraph para =td.getParagraph(k);
// String s = para.text();
// System.out.println(s);
// }
// }
// }
}
}catch(Exception e){
e.printStackTrace();
}
}
工具类,没有用到
package com.sxygsj.FileUpload; import org.apache.poi.xwpf.usermodel.*; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class WordUtil { /**
* 替换段落里面的变量
* @param doc 要替换的文档
* @param params 参数
*/
public static void replaceInPara(XWPFDocument doc, Map<String, Object> params) {
for( XWPFParagraph para : doc.getParagraphs()){
replaceInPara(para, params);
}
} /**
* 替换段落里面的变量
* @param para 要替换的段落
* @param params 参数
*/
public static void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
List<XWPFRun> runs;
Matcher matcher;
replaceText(para);//如果para拆分的不对,则用这个方法修改成正确的
if (matcher(para.getParagraphText()).find()) {
runs = para.getRuns();
for (int i=0; i<runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.toString();
matcher = matcher(runText);
if (matcher.find()) {
while ((matcher = matcher(runText)).find()) {
runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));
}
//直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
//所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。
para.removeRun(i);
para.insertNewRun(i).setText(runText);
}
}
}
} /**
* 合并runs中的内容
* @param
* @return
*/
public static List<XWPFRun> replaceText(XWPFParagraph para){
List<XWPFRun> runs = para.getRuns();
String str = "";
boolean flag = false;
for (int i=0; i<runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.toString();
if( flag || runText.equals("${") ){ str = str + runText;
flag = true;
para.removeRun(i);
if( runText.equals("}") ){
flag = false;
para.insertNewRun(i).setText(str);
str = "";
}
i--;
} } return runs;
}
/**
* 替换表格里面的变量
* @param doc 要替换的文档
* @param params 参数
*/
public static void replaceInTable(XWPFDocument doc, Map<String, Object> params) {
Iterator<XWPFTable> iterator = doc.getTablesIterator();
XWPFTable table;
List<XWPFTableRow> rows;
List<XWPFTableCell> cells;
List<XWPFParagraph> paras;
while (iterator.hasNext()) {
table = iterator.next();
rows = table.getRows();
for (XWPFTableRow row : rows) {
cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
paras = cell.getParagraphs();
for (XWPFParagraph para : paras) {
replaceInPara(para, params);
}
}
}
}
} /**
* 正则匹配字符串
* @param str
* @return
*/
public static Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
} /**
* 关闭输入流
* @param is
*/
public static void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 关闭输出流
* @param os
*/
public static void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
poi导出word文档,doc和docx的更多相关文章
- C#导出Word文档开源组件DocX
1.帮助文档,这东西找了很久,而且它版本很旧,还是英文,W8.1系统上打不开 http://download.csdn.net/detail/zuofangyouyuan/7673573 2.开源网址 ...
- SpringBoot集成文件 - 如何使用POI导出Word文档?
前文我们介绍了通过Apache POI导出excel,而Apache POI包含是操作Office Open XML(OOXML)标准和微软的OLE 2复合文档格式(OLE2)的Java API.所以 ...
- Poi之Word文档结构介绍
1.poi之word文档结构介绍之正文段落 一个文档包含多个段落,一个段落包含多个Runs,一个Runs包含多个Run,Run是文档的最小单元 获取所有段落:List<XWPFParagraph ...
- POI生成word文档完整案例及讲解
一,网上的API讲解 其实POI的生成Word文档的规则就是先把获取到的数据转成xml格式的数据,然后通过xpath解析表单式的应用取值,判断等等,然后在把取到的值放到word文档中,最后在输出来. ...
- 用java语言通过POI实现word文档的按标题提取
最近有一个项目需要将一个word文档中的数据提取到数据库中.就去网上查了好多资料,最靠谱的就是用poi实现word文档的提取. 喝水不忘挖井人,我查了好多资料就这个最靠谱,我的这篇博客主要是借鉴htt ...
- Java用freemarker导出Word 文档
1.用Microsoft Office Word打开word原件: 2.把需要动态修改的内容替换成***,如果有图片,尽量选择较小的图片几十K左右,并调整好位置: 3.另存为,选择保存类型Word 2 ...
- POI 生成 word 文档 简单版(包括文字、表格、图片、字体样式设置等)
POI 生成word 文档 一般有两种方法: ① word模板 生成word 文档 : ② 写代码直接生成 word 文档: 我这里演示的是第二种方法,即写代码生成 word文档,不多说废话,直接 ...
- POI生成WORD文档
h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h ...
- .NET通过调用Office组件导出Word文档
.NET通过调用Office组件导出Word文档 最近做项目需要实现一个客户端下载word表格的功能,该功能是用户点击"下载表格",服务端将该用户的数据查询出来并生成数据到Word ...
随机推荐
- AI领域:如何做优秀研究并写高水平论文?
来源:深度强化学习实验室 每个人从本科到硕士,再到博士.博士后,甚至工作以后,都会遇到做研究.写论文这个差事.论文通常是对现有工作的一个总结和展示,特别对于博士和做研究的人来说,论文则显得更加重要. ...
- 使用webhooks进行代码的自动化部署
AutoMaticDeployment---自动部署 项目简介 使用Github的webhooks进行代码的自动化部署 本项目是个人最近搞的一个小工具,自己最近在用hexo部署个人博客(地址:http ...
- HDU - 1962 二分图最大匹配模板(扑克牌得分最大)
题意: 直接说数据,第一行给定几组数据,每一组数据的第一行是两个人扑克牌分别的数量,第一行是亚当的扑克牌,第二行是夏娃的扑克牌,每一个扑克牌的大小用两个字符来表示,第一个表示是几号扑克牌,第二个表示扑 ...
- 使用FME裁剪矢量shapefile文件
- C++最简打开网页的方法
system("explorer https://pay.747fz.com");
- windows server 2016 远程桌面mstsc DPI(更改文本、应用和其他项目大小) 设置
windows server 2016 远程桌面mstsc DPI 设置 在高分辨率机器2K,4K,8K,登入使用window远程桌面mstsc时,登入后虽然分辨率变成了和cilent一样分辨率 但是 ...
- [noip模拟20170921]模版题
今天考的是一套很基础的模版题,但是我这种蒟蒻竟然还是没有AK,不得不说,蒟蒻和大佬的差别不是一点点啊 1.暴走的猴子(walk.pas/c/cpp) [题目描述] 从前有一个森林,森林里生活着一群 ...
- windows使用的奇淫技巧
找回刚才打开的网页 记事本 特殊符号输入 窗口变化为1/2,1/4 批量重命名 复制文件路径 万能命令
- 使用RandomString方法后,结果返回相同的随机数解决办法
所遇问题: 在做超市管理系统的登录项目时,在对“随机数的产生”出现一个问题,在产生多个随机数的时候,出现了产生了多个一样的随机数,具体代码如下: /// <summary> /// 生成随 ...
- .Net微服务实践(二):Ocelot介绍和快速开始
目录 介绍 基本原理 集成方式 快速开始 创建订单服务 创建产品服务 创建网关 运行验证 最后 上篇.Net微服务实践(一):微服务框架选型 我们对微服务框架整体做了介绍,接下来我们从网关Ocelot ...