poi导出word

1.jar包

	<dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>ooxml-schemas</artifactId>
      <version>1.3</version>
    </dependency>
	<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-scratchpad</artifactId>
      <version>3.17</version>
    </dependency>
	<dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-excelant</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-examples</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
    <dependency>

2.工具类

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class WordUtils {
	 /**
	     * 替换所有段落中的标记
	     *
	     * @param xwpfParagraphList
	     * @param params
	     */
	    public static void replaceInAllParagraphs(List<XWPFParagraph> xwpfParagraphList, Map<String, String> params) {
	        for (XWPFParagraph paragraph : xwpfParagraphList) {
	            if (paragraph.getText() == null || paragraph.getText().equals("")) continue;
	            for (String key : params.keySet()) {
	                if (paragraph.getText().contains(key)) {
	                    replaceInParagraph(paragraph, key, params.get(key));
	                }
	            }
	        }
	    }
	 
	    /**
	     * 替换段落中的字符串
	     *
	     * @param xwpfParagraph
	     * @param oldString
	     * @param newString
	     */
	    public static void replaceInParagraph(XWPFParagraph xwpfParagraph, String oldString, String newString) {
	        Map<String, Integer> pos_map = findSubRunPosInParagraph(xwpfParagraph, oldString);
	        if (pos_map != null) {
	            List<XWPFRun> runs = xwpfParagraph.getRuns();
	            XWPFRun modelRun = runs.get(pos_map.get("end_pos"));
	            XWPFRun xwpfRun = xwpfParagraph.insertNewRun(pos_map.get("end_pos") + 1);
	            xwpfRun.setText(newString);
	            if (modelRun.getFontSize() != -1)
	                xwpfRun.setFontSize(modelRun.getFontSize());//默认值是五号字体,但五号字体getFontSize()时,返回-1
	            xwpfRun.setFontFamily(modelRun.getFontFamily());
	            for (int i = pos_map.get("end_pos"); i >= pos_map.get("start_pos"); i--) {
	                xwpfParagraph.removeRun(i);
	            }
	        }
	    }
	 
	    /**
	     * 找到段落中子串的起始XWPFRun下标和终止XWPFRun的下标
	     *
	     * @param xwpfParagraph
	     * @param substring
	     * @return
	     */
	    public static Map<String, Integer> findSubRunPosInParagraph(XWPFParagraph xwpfParagraph, String substring) {
	        List<XWPFRun> runs = xwpfParagraph.getRuns();
	        int start_pos = 0;
	        int end_pos = 0;
	        String subtemp = "";
	        for (int i = 0; i < runs.size(); i++) {
	            subtemp = "";
	            start_pos = i;
	            for (int j = i; j < runs.size(); j++) {
	                if (runs.get(j).getText(runs.get(j).getTextPosition()) == null) continue;
	                subtemp += runs.get(j).getText(runs.get(j).getTextPosition());
	                if (subtemp.equals(substring)) {
	                    end_pos = j;
	                    Map<String, Integer> map = new HashMap<>();
	                    map.put("start_pos", start_pos);
	                    map.put("end_pos", end_pos);
	                    return map;
	                }
	            }
	        }
	        return null;
	    }
	 
	    /**
	     * 替换所有的表格
	     *
	     * @param xwpfTableList
	     * @param params
	     */
	    public static void replaceInTables(List<XWPFTable> xwpfTableList, Map<String, String> params) {
	        for (XWPFTable table : xwpfTableList) {
	            replaceInTable(table, params);
	        }
	    }
	 
	    /**
	     * 替换一个表格中的所有行
	     *
	     * @param xwpfTable
	     * @param params
	     */
	    public static void replaceInTable(XWPFTable xwpfTable, Map<String, String> params) {
	        List<XWPFTableRow> rows = xwpfTable.getRows();
	        replaceInRows(rows, params);
	    }
	 
	    /**
	     * 替换表格中的一行
	     *
	     * @param rows
	     * @param params
	     */
	    public static void replaceInRows(List<XWPFTableRow> rows, Map<String, String> params) {
	        for (int i = 0; i < rows.size(); i++) {
	            XWPFTableRow row = rows.get(i);
	            replaceInCells(row.getTableCells(), params);
	        }
	    }
	 
	    /**
	     * 替换一行中所有的单元格
	     *
	     * @param xwpfTableCellList
	     * @param params
	     */
	    public static void replaceInCells(List<XWPFTableCell> xwpfTableCellList, Map<String, String> params) {
	        for (XWPFTableCell cell : xwpfTableCellList) {
	            replaceInCell(cell, params);
	        }
	    }
	 
	    /**
	     * 替换表格中每一行中的每一个单元格中的所有段落
	     *
	     * @param cell
	     * @param params
	     */
	    public static void replaceInCell(XWPFTableCell cell, Map<String, String> params) {
	        List<XWPFParagraph> cellParagraphs = cell.getParagraphs();
	        replaceInAllParagraphs(cellParagraphs, params);
	     }
	    }

3.controlelr层

/**
	 * poi下载导出
	 *
	 * @param reportClue
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/download")
	@ResponseBody
	public List<Object> download(ReportClue reportClue, HttpServletRequest request, HttpServletResponse response) {
		try {
			ReportClue reportClueInfo = reportClueService.getById(ReportClue.class, reportClue.getId());
			// ExcelUtiles excelUtiles = new ExcelUtiles();
			Map<String, String> params = new HashMap<>();
			params.put("${name}", reportClueInfo.getName());
			params.put("${phone}", reportClueInfo.getPhone());
			params.put("${content}", reportClueInfo.getContent());
			params.put("${money}", reportClueInfo.getMoney().toString());
			// excelUtiles.exportWord("分局举报奖励审批表.docx",
			// ParseProperties.getProperties().get("fileTemplateUrlword").toString(),
			// params, request, response);
			WordUtils wordUtil = new WordUtils();
			String filePath = ParseProperties.getProperties().get("fileTemplateUrlword").toString() + "分局举报奖励审批表.docx";
			String fileName = PbUtils.getCurrentTime() + "分局举报奖励审批表.docx";
			OPCPackage pack = POIXMLDocument.openPackage(filePath);// 读取模板文件
			XWPFDocument document = new XWPFDocument(pack);// 创建word文件并将模板导入
			// 对段落中的标记进行替换
			List<XWPFParagraph> parasList = document.getParagraphs();
			wordUtil.replaceInAllParagraphs(parasList, params);
			// 表格标记替换
			List<XWPFTable> tables = document.getTables();
			wordUtil.replaceInTables(tables, params);
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName).getBytes(), "iso-8859-1"));
			OutputStream out = response.getOutputStream();
			document.write(out);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return null;
	}
	
4.模板
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191206171148742.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyNjgyMzAy,size_16,color_FFFFFF,t_70)
	
5.导出示例

![在这里插入图片描述](https://img-blog.csdnimg.cn/20191206171052244.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyNjgyMzAy,size_16,color_FFFFFF,t_70)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值