poi导出word文档,doc和docx

时间:2021-06-06 12:10:36

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();
}
}
} }