博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java工具类POI导出word
阅读量:6270 次
发布时间:2019-06-22

本文共 7837 字,大约阅读时间需要 26 分钟。

 

1、新建一个word,里面填写内容,如:

2、导出wordjava类

/**     * POI导出word测试     * @throws Exception     */    @RequestMapping(value="exportApplyForm")     public void exportApplyForm(HttpServletResponse response) throws Exception {                        Map
params = new HashMap
(); params.put("${name}", "1"); params.put("${sex}","1"); params.put("${political}", "1"); params.put("${place}", "1"); params.put("${classes}", "1"); params.put("${id}", "1"); params.put("${qq}", "1"); params.put("${tel}", "1"); params.put("${oldJob}", "1"); params.put("${swap}", "1"); params.put("${first}", "1"); params.put("${second}", "1"); params.put("${award}", "1"); params.put("${achievement}", "1"); params.put("${advice}", "1"); params.put("${attach}", "1"); XwpfTUtil xwpfTUtil = new XwpfTUtil(); XWPFDocument doc; String fileNameInResource = "sta.docx"; InputStream is; /*is = new FileInputStream(filePath);*/ is = getClass().getClassLoader().getResourceAsStream(fileNameInResource); //本身就在编译路径下。。。。 doc = new XWPFDocument(is); xwpfTUtil.replaceInPara(doc, params); //替换表格里面的变量 xwpfTUtil.replaceInTable(doc, params); OutputStream os = response.getOutputStream(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition","attachment;filename=测试.docx"); doc.write(os); xwpfTUtil.close(os); xwpfTUtil.close(is); os.flush(); os.close(); }

 

3、文件工具类

package util;    import org.apache.poi.xwpf.usermodel.*;  import org.junit.Test;    import java.io.*;  import java.util.HashMap;  import java.util.Iterator;  import java.util.List;  import java.util.Map;  import java.util.regex.Matcher;  import java.util.regex.Pattern;    public class XwpfTUtil {        /*String filePath = "/sta.docx";     InputStream is;     XWPFDocument doc;     Map
params = new HashMap
(); { params.put("${name}", "xxx"); params.put("${sex}", "男"); params.put("${political}", "共青团员"); params.put("${place}", "sssss"); params.put("${classes}", "3102"); params.put("${id}", "213123123"); params.put("${qq}", "213123"); params.put("${tel}", "312313213"); params.put("${oldJob}", "sadasd"); params.put("${swap}", "是"); params.put("${first}", "asdasd"); params.put("${second}", "综合事务部"); params.put("${award}", "asda"); params.put("${achievement}", "完成科协网站的开发"); params.put("${advice}", "没有建议"); params.put("${attach}", "无"); try { is = new FileInputStream(filePath); doc = new XWPFDocument(is); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }*/ /** * 用一个docx文档作为模板,然后替换其中的内容,再写入目标文档中。 * * @throws Exception */ /*@Test public void testTemplateWrite() throws Exception { //替换段落里面的变量 this.replaceInPara(doc, params); //替换表格里面的变量 this.replaceInTable(doc, params); OutputStream os = new FileOutputStream("D:\\sta1.docx"); doc.write(os); this.close(os); this.close(is); }*/ /*@Test public void myTest1() throws Exception { *//*Iterator
iterator = doc.getParagraphsIterator(); XWPFParagraph para; while (iterator.hasNext()) { para = iterator.next(); List
runs = para.getRuns(); para.removeRun(0); para.insertNewRun(0).setText("hello"); } OutputStream os = new FileOutputStream("D:\\sta1.docx"); doc.write(os); this.close(os); this.close(is);*//* System.out.println(this.matcher("报告日期:${reportDate}").find()); }*/ /*@Test public void myReplaceInPara() { // Iterator
iterator = doc.getParagraphsIterator(); // XWPFParagraph para; // while (iterator.hasNext()) { // para = iterator.next(); // List
runs = para.getRuns(); // // // } System.out.println('{'=='{'); }*/ /** * 替换段落里面的变量 * * @param doc 要替换的文档 * @param params 参数 */ public void replaceInPara(XWPFDocument doc, Map
params) { Iterator
iterator = doc.getParagraphsIterator(); XWPFParagraph para; while (iterator.hasNext()) { para = iterator.next(); this.replaceInPara(para, params); } } /** * 替换段落里面的变量 * * @param para 要替换的段落 * @param params 参数 */ public void replaceInPara(XWPFParagraph para, Map
params) { List
runs; Matcher matcher; if (this.matcher(para.getParagraphText()).find()) { runs = para.getRuns(); int start = -1; int end = -1; String str = ""; for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); String runText = run.toString(); System.out.println("------>>>>>>>>>" + runText); if ('$' == runText.charAt(0)&&'{' == runText.charAt(1)) { start = i; } if ((start != -1)) { str += runText; } if ('}' == runText.charAt(runText.length() - 1)) { if (start != -1) { end = i; break; } } } System.out.println("start--->"+start); System.out.println("end--->"+end); System.out.println("str---->>>" + str); for (int i = start; i <= end; i++) { para.removeRun(i); i--; end--; System.out.println("remove i="+i); } for (String key : params.keySet()) { if (str.equals(key)) { para.createRun().setText((String) params.get(key)); break; } } } } /** * 替换表格里面的变量 * * @param doc 要替换的文档 * @param params 参数 */ public void replaceInTable(XWPFDocument doc, Map
params) { Iterator
iterator = doc.getTablesIterator(); XWPFTable table; List
rows; List
cells; List
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) { this.replaceInPara(para, params); } } } } } /** * 正则匹配字符串 * * @param str * @return */ private Matcher matcher(String str) { Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(str); return matcher; } /** * 关闭输入流 * * @param is */ public void close(InputStream is) { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 关闭输出流 * * @param os */ public void close(OutputStream os) { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }

4、maven对应的jar包

org.apache.poi
poi
3.10-beta2
jar
compile
org.apache.poi
poi-ooxml
3.10-beta2
jar
org.apache.poi
poi-ooxml-schemas
3.10-beta2
jar
compile
org.apache.poi
poi-scratchpad
3.0.2-FINAL

 

转载地址:http://lnppa.baihongyu.com/

你可能感兴趣的文章
欧几里德算法与扩展欧几里德算法
查看>>
Tinkoff Internship Warmup Round 2018 and Codeforces Round #475 (Div. 2)
查看>>
通过kafka提供的命令来查看offset消费情况
查看>>
oracle数据库从入门到精通之四
查看>>
自定义圆形图片控件
查看>>
sharepoint 2013 补丁升级步骤
查看>>
asp.net core 2.0 web api基于JWT自定义策略授权
查看>>
Skype for Business Server 2015-04-前端服务器-3-安装-管理工具
查看>>
第12章代码《跟老男孩学习Linux运维:Shell编程实战》
查看>>
我们为什么从Python转到go?
查看>>
5.Azure负载均衡(上)
查看>>
轻松精通awk数组企业问题案例
查看>>
26.Azure备份服务器(下)
查看>>
从“网上说的能信么”说开去---学习的思考
查看>>
DHCP 日志分析
查看>>
.NET Micro Framework动态调用C/C++底层代码(原理篇)
查看>>
Windows Server 2012正式版RDS系列⒃
查看>>
Shell脚本之awk篇
查看>>
微软发布Azure Stack硬件需求
查看>>
python socket编程详细介绍
查看>>