JAVA POI Word模板动态数据填充并下载(不包含图片,仅限文本)

除了POI的JAR包还需要引入:

<dependency>
	<groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
	<version>1.0.6</version>
</dependency>
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
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;
  
  /**
   * 文件数据替换
   * @author 23  *
   */
  
  public class ReplaceWordUtil {
  
      public static String path = "模板文件的路径/word.docx";
  
      public static void main(String[] args) throws Exception {
          Map<String, Object> data = new HashMap<>();
          data.put("${seal}", "1");  
          getWordMain(data);
      }

	  public static void getWordMain(Map<String, Object> data) throws Exception {
         try (FileInputStream is = new FileInputStream(path); XWPFDocument document = new XWPFDocument(is)) {
             // 替换掉表格之外的文本(仅限文本)
             changeText(document, data);
             // 替换表格内的文本对象
             changeTableText(document, data);
             long time = System.currentTimeMillis();// 获取系统时间
             System.out.println(time); // 打印时间
             // 使用try和catch关键字捕获异常
             try (FileOutputStream out = new FileOutputStream("D:/word-"+time + ".docx")) {
                 document.write(out);
             }
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         }
     }
      /**
	     * 
	     * Description:获取word重新赋值并获取到供下载的流信息
	     * @param downloadDto
	     * @param Object 需要赋值的信息
	     * @return void
	     * @throws Exception
	     *
	     */
	  public static ByteArrayOutputStream writeWord(Object obj, String path, HttpServletResponse response,String downloadName)
            throws Exception {
        Map<String, Object> data = new HashMap<>();
        data.put("${seal}", obj.属性值);  
		FileInputStream is = null;
		ByteArrayOutputStream baos = null;
        try {
        	is = new FileInputStream(path);
        	XWPFDocument document = new XWPFDocument(is);
            // 替换掉表格之外的文本(仅限文本)
            changeText(document, data);
            // 替换表格内的文本对象
            changeTableText(document, data);
		
			baos = new ByteArrayOutputStream();
			document.write(baos);// 临时存储流到内存
	        baos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
        	if(is != null){
        		is.close();
        	}
        	if(baos != null){
        		baos.close();
        	}
        	if(out != null){
        		out.close();
        	}
        }
    }

	/**
     * 
     * Description:下载转换成流的word文件
     * @param filePath
     * @param fileName
     * @param response
     * @param baos
     * @throws IOException
     * @return void
     *
     */
	public static void downloadWord(String fileName, HttpServletResponse response, ByteArrayOutputStream baos) throws IOException 
	{
		 OutputStream out = null;
		 try {
			 response.setContentType("octets/stream");
			 response.addHeader("Content-Type", "text/html; charset=utf-8");
			 String downLoadName = new String(fileName.getBytes("gbk"), "iso8859-1");
			 response.addHeader("Content-Disposition", "attachment;filename=" + downLoadName);
			 byte[] bytes = baos.toByteArray();		 
			 out = new BufferedOutputStream(response.getOutputStream());
			 out.write(bytes);
		 } catch (Exception e) {
			 e.printStackTrace();
         }finally{
        	if(baos != null){
        		baos.close();
        	}
        	if(out != null){
        		out.close();
        	}
        }
		
	}

版权声明:本文为weixin_39093006原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。