POI 正常输出WORD 文档

package com.wdit.linsheng.modules.cms.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.utils.DateUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import com.wdit.linsheng.common.config.Global;
import com.wdit.linsheng.modules.cms.entity.Complain;


public class WordUtil {
     static Logger logger = Logger.getLogger(WordUtil.class);
    
     private static WordUtil wordUtil = null;

     /**
     * 私有构造
     */
     private WordUtil() {

     }
    
     public static WordUtil getInstance() {
          if (wordUtil == null) {
               wordUtil = new WordUtil();
          }
          return wordUtil;
     }

     /**
     * 方法描述:下载文件
     * @param response
     * @param rootPath
     * @param targetName
     * @param fileName
     * @param module
     * @throws IOException
     */
     public void downloadFile(String path, String downLoadFileName,HttpServletResponse response)  {
          try {
               File file = new File(path);
               if (!file.exists()) {
                    return;
               }
         
               file = new File(path + downLoadFileName);
               InputStream fis = new BufferedInputStream(new FileInputStream(file));
              
               //buffer 中间缓冲池
               byte[] buffer = new byte[fis.available()];
               fis.read(buffer);
               fis.close();
              
               //保存为word
               //String tragetFileName = downLoadFileName + ".doc";
              
               // 清空response
               response.reset();
               // 设置response的Header
               response.addHeader("Content-Disposition",
                         "attachment;filename=" + downLoadFileName);//URLEncoder.encode());//, "UTF-8"
               
// 设置response的Header 如果文件名参数中含有中文的写法
//response.addHeader( "Content-Disposition",
  //   "attachment;filename=" + new String(downLoadFileName.getBytes("gb2312"), "ISO8859-1"));

               response.addHeader("Content-Length", "" + file.length());
               OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
               response.setContentType("text/plain");
               toClient.write(buffer);
               toClient.flush();
               toClient.close();
          } catch (IOException e) {
               e.printStackTrace();
          }
     }
    
     /**
     * 创建 投诉热线 word文档
     * @param list
     * @param response
     * @return
     */
     public static String createComplain(List<Complain> list) {
        try {
             XWPFDocument doc = new XWPFDocument();
               XWPFParagraph p1 = doc.createParagraph();
               //设置段落左对齐
               p1.setAlignment(ParagraphAlignment.LEFT);
               XWPFRun r1 = p1.createRun();
               for (Complain complain : list) {
                    r1.setText("时间:");
                    r1.setText(DateUtils.formatDate(complain.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
//                    r1.addBreak();
                    r1.setText("地点:");
                    r1.setText(complain.getAddress());
//                    r1.addBreak();
                    r1.setText("内容:");
//                    r1.addBreak();
                    r1.setText(complain.getContent());
                    r1.setText("姓名:");
                    r1.setText(complain.getName());
//                    r1.addBreak();
                    r1.setText("电话:");
                    r1.setText(complain.getPhone());
//                    r1.addBreak();
                    r1.setText("是否公开:");
                    r1.setText(complain.getIsPublic());
//                    r1.addBreak();
                    r1.setText("信息补充:");
//                    r1.addBreak();
                    r1.setText(complain.getYjComm());
                   r1.setTextPosition(100); 
               }
               String fileName = Global.getWebProjectPath() + File.separator + "doc" + File.separator + list.get(0).getTitle() + ".doc" ;
               File tempFile = new File(fileName);
               if (tempFile.exists()) {
                    tempFile.delete();
               }
               FileOutputStream out = new FileOutputStream(fileName); 
               doc.write(out); 
               out.close();
               return list.get(0).getTitle() + ".doc";
          } catch (Exception e) {
               logger.error("exportWordError:" + e);
               e.printStackTrace();
               return null;
          }
       
    } 
    
     /**
     * 利用模板创建投诉热线WORD
     * @param list
     * @return
     */
     public static String createComplainWord(List<Complain> list){ 
           try {
                String templatePath = Global.getWebProjectPath() + File.separator + "doc" + File.separator + "compTemplete.doc"; 
                 InputStream is = new FileInputStream(templatePath); 
                 HWPFDocument doc = new HWPFDocument(is); 
                 Range range = doc.getRange();
                 Complain complain = list.get(0);
                 //把range范围内的${param}替换为对应参数
                 range.replaceText("${incidentDate}", DateUtils.formatDate(complain.getIncidentDate(), "yyyy-MM-dd HH:mm:ss")); 
                 range.replaceText("${location}", complain.getLocation()); 
                 range.replaceText("${content}", complain.getContent()); 
                 range.replaceText("${name}", complain.getName());
                 range.replaceText("${phone}", complain.getPhone());
                 range.replaceText("${isPublic}", "1".equals(complain.getIsPublic()) ? "" : "");
                 String fileName = Global.getWebProjectPath() + File.separator + "doc" + File.separator + list.get(0).getTitle() + ".doc" ;
                 File tempFile = new File(fileName);
                 if (tempFile.exists()) {
                         tempFile.delete();
                 }
                 tempFile.createNewFile();
                 OutputStream os = new FileOutputStream(fileName);
                 //把doc输出到输出流中 
                 doc.write(os); 
                 closeStream(os); 
                 closeStream(is);
                 return list.get(0).getTitle() + ".doc";
          } catch (Exception e) {
               logger.error("exportWordError:" + e);
               e.printStackTrace();
               return null;
          } 
       }  
    
       /**
         * 关闭输入流
         * @param is
         */ 
       private static void closeStream(InputStream is) { 
           if (is != null) { 
              try { 
                 is.close(); 
              } catch (IOException e) { 
                 e.printStackTrace(); 
              } 
           } 
        } 
       
        /**
         * 关闭输出流
         * @param os
         */ 
        private static void closeStream(OutputStream os) { 
           if (os != null) { 
              try { 
                 os.close(); 
              } catch (IOException e) { 
                 e.printStackTrace(); 
              } 
           } 
        } 
        
    
}
原文地址:https://www.cnblogs.com/leonkobe/p/6473041.html