apache.poi package simple operation word document

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.Range;

/**
 * Word document manipulation tool
 * Created by lichunlong on 2015/5/6 0006.
 */
 public class WordUtil {
     /**
      * Modify word and save it locally
 * @param map key-value pair that needs to be modified
 */
 public static void writeAndSave(Map<String, String> map) {
         try {
             // Read word template
 String fileDir = new File( "C: \\ Users \\ Administrator \\ Desktop \\ file" ).getCanonicalPath();
            FileInputStream inputStream = new FileInputStream(new File(fileDir+"\\template.doc"));
            HWPFDocument doc = new HWPFDocument(inputStream);
//            Fields fields = doc.getFields();
//            Iterator<Field> ite = fields.getFields(FieldsDocumentPart.MAIN).iterator();
//            while(ite.hasNext()){
//                System.out.println(ite.next().getType());
//            }
            //读取word文本内容
Range range = doc.getRange();
//       System.out.println(range.text());
            //替换文本内容
for (Map.Entry<String,String> entry : map.entrySet()) {
                range.replaceText(entry.getKey(), entry.getValue());
            }

            //输出字节流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            String fileName = ""+System.currentTimeMillis();
            fileName += ".doc";
            FileOutputStream out = new FileOutputStream(fileDir+"\\"+fileName,true);
            doc.write(outputStream);
            out.write(outputStream.toByteArray());
            out.close();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

    /**
      * Modify word and provide download
 * @param request
 * @param response
 * @param map key-value pair that needs to be modified
 * @throws ServletException
      * @throws IOException
      */
 public static void writeAndPost(HttpServletRequest request, HttpServletResponse response, Map< String, String> map) throws ServletException, IOException{
         try {

            // Read word template file
 String fileDir = new File( "C: \\ Users \\ Administrator \\ Desktop \\ file" ).getCanonicalPath();
            FileInputStream inputStream = new FileInputStream(new File(fileDir+"\\template.doc"));
            HWPFDocument doc = new HWPFDocument(inputStream);

            // Replace the specified field of the read word template content
 Range range = doc.getRange();
             for (Map.Entry<String,String> entry : map.entrySet()) {
                range.replaceText(entry.getKey(), entry.getValue());
            }

            // Output word content file stream, provide download
 response.reset();
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename=\"test.doc\"");
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ServletOutputStream servletOutputStream = response.getOutputStream();
            doc.write(outputStream);
            servletOutputStream.write(outputStream.toByteArray());
            servletOutputStream.flush();
            servletOutputStream.close();

        } catch (IOException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }finally{

        }
    }
}

Dynamically set the file name to solve the problem of Chinese garbled characters:
response.setCharacterEncoding("utf-8");
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment; filename="+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326989651&siteId=291194637