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 ...
随机推荐
- 题解 P1052 【过河】
显然是\(dp\),是用\(STL\)当中的\(map\)可以做到30分 #include <bits/stdc++.h>//万能头文件 using namespace std; int ...
- Building Applications with Force.com and VisualForce (DEV401) (二二):Visualforce Componets (Tags) Library Part II
Dev401-023:Visualforce Pages: Visualforce Componets (Tags) Library Part II Apex:pageBlockTable1.A ...
- OpenCV-Python 轮廓:入门 | 二十一
目标 了解轮廓是什么. 学习查找轮廓,绘制轮廓等. 你将看到以下功能:cv.findContours(),cv.drawContours() 什么是轮廓? 轮廓可以简单地解释为连接具有相同颜色或强度的 ...
- CSRF的几种防御方法的利弊分析
本文直接从防御方式开始讨论,防御CSRF有4种方法: 使用POST替代GET 检验HTTP Referer 验证码 Token 使用POST替代GET 一些程序员在开发的时候都是用GET.POST通用 ...
- coding++ :JS对日期的神操作封装版
格式化日期: /** * 格式化日期 * @param fmt 例如:yyyy-MM-dd 等 * @returns {*} * @constructor */ Date.prototype.Form ...
- Java构造器(构造方法/constructor)
我们先来看一下什么是构造器: 1.构造器也叫构造方法或构造函数,分为有参构造器和无参构造器: 2.构造器也是一种方法,只不过是一种特殊的方法,它会在对象创建的时候被调用: 3.构造器最大的作用就是在创 ...
- Java实验五参考答案
1.找错误 btOK.setOnAction( new EventHandler<ActionEvent> { public void handle (ActionEvent e) { S ...
- 轻轻松松了解Java的初始化方法(含对象数组的小问题)
Java基础复习6-初始化 之前讲过了类的一些基础,想必大家都知道了类的定义 什么?你忘了? 下面给你一个例子快速复习 class AClass{ int a; boolean b; void get ...
- vue引入echart Error in mounted hook: "ReferenceError: myChart is not defined" found in
解决办法: // 实例化echarts对象 var/let myChart = echarts.init(this.$refs.myChart)
- WTM asp.net core应用程序在Ubuntu上和CentOS上部署
wtm在Ubuntu上和CentOS上部署 项目发布 在Visual Studio中右击Web项目,选择发布,如下图: Ubuntu安装.net core运行时 Ubuntu我是用的Vmware虚拟机 ...