使用POI导出为word并打包为zip下载

本文介绍了一种使用Apache POI库批量创建Word文档的方法,并将其压缩为ZIP文件供下载。通过定制XWPFDocument类来实现图片插入等功能,同时展示了如何根据项目论文内容自动填充文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用POI导出为word并打包为zip下载

先前要做一个功能:导出并压缩多个word文档,于是发现了导出word的6种方式:http://www.cnblogs.com/lcngu/p/5247179.html
虽然都说poi不适合用来导出word,但是还是义无反顾的用了poi,下面正题。

package com.qinghuainvest.export.web;

import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
//重写XWPFDocument的方法,插入图片
public class CustomXWPFDocument extends XWPFDocument{
    public CustomXWPFDocument() {  
        super();  
    }  

    public CustomXWPFDocument(OPCPackage opcPackage) throws IOException {  
        super(opcPackage);  
    }  

    public CustomXWPFDocument(InputStream in) throws IOException {  
        super(in);  
    }  

    public void createPicture(String blipId,int id, int width, int height) {  
        final int EMU = 9525;  
        width *= EMU;  
        height *= EMU;  
        //String blipId = getAllPictures().get(id).getPackageRelationship().getId();  


        CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline();  

        String picXml = "" +  
                "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +  
                "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +  
                "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +  
                "         <pic:nvPicPr>" +  
                "            <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +  
                "            <pic:cNvPicPr/>" +  
                "         </pic:nvPicPr>" +  
                "         <pic:blipFill>" +  
                "            <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +  
                "            <a:stretch>" +  
                "               <a:fillRect/>" +  
                "            </a:stretch>" +  
                "         </pic:blipFill>" +  
                "         <pic:spPr>" +  
                "            <a:xfrm>" +  
                "               <a:off x=\"0\" y=\"0\"/>" +  
                "               <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +  
                "            </a:xfrm>" +  
                "            <a:prstGeom prst=\"rect\">" +  
                "               <a:avLst/>" +  
                "            </a:prstGeom>" +  
                "         </pic:spPr>" +  
                "      </pic:pic>" +  
                "   </a:graphicData>" +  
                "</a:graphic>";  

        //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();  
        XmlToken xmlToken = null;  
        try {  
            xmlToken = XmlToken.Factory.parse(picXml);  
        } catch(XmlException xe) {  
            xe.printStackTrace();  
        }  
        inline.set(xmlToken);  
        //graphicData.set(xmlToken);  

        inline.setDistT(0);  
        inline.setDistB(0);  
        inline.setDistL(0);  
        inline.setDistR(0);  

        CTPositiveSize2D extent = inline.addNewExtent();  
        extent.setCx(width);  
        extent.setCy(height);  

        CTNonVisualDrawingProps docPr = inline.addNewDocPr();  
        docPr.setId(id);  
        docPr.setName("Picture " + id);  
        docPr.setDescr("Generated");  
    }
}

    @ResponseBody
    @RequestMapping("exportWord")
    public void exportWord(String ids,HttpServletResponse resp) {
        String projectId= ShiroUtils.getShiroUser().getProjectId();
        try {
            List<ProjectPaper> paperList=paperService.findByIds(ids);
            managePaperCode(paperList,projectId);


            for (ProjectPaper projectPaper : paperList) {
                CustomXWPFDocument  document= new CustomXWPFDocument ();  
                XWPFParagraph titleParagraph = document.createParagraph();  
                titleParagraph.setAlignment(ParagraphAlignment.LEFT);  
                XWPFRun titleParagraphRun = titleParagraph.createRun();  
                titleParagraphRun.setText(projectPaper.getPaperCode());
                titleParagraphRun.setFontSize(10);
                titleParagraphRun.setFontFamily("Arial");
                //段落
                XWPFParagraph firstParagraph = document.createParagraph();  
                XWPFRun run = firstParagraph.createRun();
                run.setText(projectPaper.getPaperformContent().getTitle());  
                run.setFontSize(8);
                run.setBold(true);
                if(projectPaper.getPaperformContent().getTitle().matches("[\\u4E00-\\u9FA5]+")) {
                    run.setFontFamily("宋体");
                }else {
                    run.setFontFamily("Times");
                }

                XWPFParagraph paragraph2 = document.createParagraph();  
                Set<ProjectPaperAuthor> projectPaperAuthorList=projectPaper.getAuthorSet();
                XWPFParagraph paragraph3 = document.createParagraph();//作者地址段
                int i=1;
                for (ProjectPaperAuthor projectPaperAuthor : projectPaperAuthorList) {
                    XWPFRun run1 = paragraph2.createRun();
                    run1.setFontSize(8);
                    run1.setText(projectPaperAuthor.getName());  
                    run1.setFontFamily("Times");
                    if(projectPaperAuthor.getName().matches("[\\u4E00-\\u9FA5]+")) {
                        run1.setFontFamily("宋体");
                    }else {
                        run1.setFontFamily("Times");
                    }
                    if(projectPaperAuthor.getIsPublishAuthor()==1) {
                        run1.setUnderline(UnderlinePatterns.SINGLE);  
                    }
                    XWPFRun run2 = paragraph2.createRun();
                    String top="";
                    if(projectPaperAuthor.getPost1()!=null) {
                        top=top+i+" ";
                        XWPFRun run31 = paragraph3.createRun();
                        run31.setText(""+i);
                        run31.setFontSize(8);
                        run31.setSubscript(VerticalAlign.SUPERSCRIPT);
                        run31.setFontFamily("Times");
                        run31.setItalic(true);
                        XWPFRun run32 = paragraph3.createRun();
                        run32.setFontFamily("Times");
                        run32.setFontSize(8);
                        run32.setText(projectPaperAuthor.getPost1().getPost()+"; ");
                        run32.setItalic(true);
                        if(projectPaperAuthor.getPost1().getPost().matches("[\\u4E00-\\u9FA5]+")) {
                            run32.setFontFamily("宋体");
                        }else {
                            run32.setFontFamily("Times");
                        }
                        i++;
                    }
                    if(projectPaperAuthor.getPost2()!=null) {
                        top=top+i+" ";
                        XWPFRun run31 = paragraph3.createRun();
                        run31.setText(""+i);
                        run31.setFontSize(8);
                        run31.setSubscript(VerticalAlign.SUPERSCRIPT);
                        run31.setFontFamily("Times");
                        run31.setItalic(true);
                        XWPFRun run32 = paragraph3.createRun();
                        run32.setFontFamily("Times");
                        run32.setFontSize(8);
                        run32.setItalic(true);
                        run32.setText(projectPaperAuthor.getPost2().getPost()+"; ");
                        if(projectPaperAuthor.getPost2().getPost().matches("[\\u4E00-\\u9FA5]+")) {
                            run32.setFontFamily("宋体");
                        }else {
                            run32.setFontFamily("Times");
                        }
                        i++;
                    }
                    if(projectPaperAuthor.getPost3()!=null) {
                        top=top+i+" ";
                        XWPFRun run31 = paragraph3.createRun();
                        run31.setText(""+i);
                        run31.setFontSize(8);
                        run31.setSubscript(VerticalAlign.SUPERSCRIPT);
                        run31.setFontFamily("Times");
                        run31.setItalic(true);
                        XWPFRun run32 = paragraph3.createRun();
                        run32.setFontFamily("Times");
                        run32.setFontSize(8);
                        run32.setItalic(true);
                        run32.setText(projectPaperAuthor.getPost3().getPost()+"; ");
                        if(projectPaperAuthor.getPost3().getPost().matches("[\\u4E00-\\u9FA5]+")) {
                            run32.setFontFamily("宋体");
                        }else {
                            run32.setFontFamily("Times");
                        }
                        i++;
                    }
                    run2.setText(top);
                    run2.setFontSize(8);
                    if(top.matches("[\\u4E00-\\u9FA5]+")) {
                        run2.setFontFamily("宋体");
                    }else {
                        run2.setFontFamily("Times");
                    }
                    run2.setSubscript(VerticalAlign.SUPERSCRIPT);
                    XWPFRun run4 = paragraph2.createRun();
                    run4.setText(",");
                    run4.setFontSize(8);
                }
                if(projectPaper.getPaperformContent().getBackground()!=null) {
                    XWPFParagraph paragraph4 = document.createParagraph();
                    XWPFRun run4 = paragraph4.createRun();
                    run4.setText("Background:");
                    run4.setFontSize(8);
                    run4.setBold(true);
                    XWPFRun run5 = paragraph4.createRun();
                    run5.setText(toPlainText(projectPaper.getPaperformContent().getBackground()));
                    run5.setFontSize(8);
                    if(toPlainText(projectPaper.getPaperformContent().getBackground()).matches("[\\u4E00-\\u9FA5]+")) {
                        run4.setFontFamily("宋体");
                        run5.setFontFamily("宋体");
                    }else {
                        run4.setFontFamily("Times");
                        run5.setFontFamily("Times");
                    }
                }
                if(projectPaper.getPaperformContent().getMethod()!=null) {
                    XWPFParagraph paragraph4 = document.createParagraph();
                    XWPFRun run4 = paragraph4.createRun();
                    run4.setText("Method:");
                    run4.setFontSize(8);
                    run4.setBold(true);
                    XWPFRun run5 = paragraph4.createRun();
                    run5.setText(toPlainText(projectPaper.getPaperformContent().getMethod()));
                    run5.setFontSize(8);
                    if(toPlainText(projectPaper.getPaperformContent().getMethod()).matches("[\\u4E00-\\u9FA5]+")) {
                        run4.setFontFamily("宋体");
                        run5.setFontFamily("宋体");
                    }else {
                        run4.setFontFamily("Times");
                        run5.setFontFamily("Times");
                    }
                }
                if(projectPaper.getPaperformContent().getResult()!=null) {
                    XWPFParagraph paragraph4 = document.createParagraph();
                    XWPFRun run4 = paragraph4.createRun();
                    run4.setText("Result:");
                    run4.setFontSize(8);
                    run4.setBold(true);
                    XWPFRun run5 = paragraph4.createRun();
                    run5.setText(toPlainText(projectPaper.getPaperformContent().getResult()));
                    run5.setFontSize(8);
                    if(toPlainText(projectPaper.getPaperformContent().getResult()).matches("[\\u4E00-\\u9FA5]+")) {
                        run4.setFontFamily("宋体");
                        run5.setFontFamily("宋体");
                    }else {
                        run4.setFontFamily("Times");
                        run5.setFontFamily("Times");
                    }
                }
                if(projectPaper.getPaperformContent().getConclusion()!=null) {
                    XWPFParagraph paragraph4 = document.createParagraph();
                    XWPFRun run4 = paragraph4.createRun();
                    run4.setText("Conclusion:");
                    run4.setFontSize(8);
                    run4.setBold(true);
                    XWPFRun run5 = paragraph4.createRun();
                    run5.setText(toPlainText(projectPaper.getPaperformContent().getConclusion()));
                    run5.setFontSize(8);
                    if(toPlainText(projectPaper.getPaperformContent().getConclusion()).matches("[\\u4E00-\\u9FA5]+")) {
                        run4.setFontFamily("宋体");
                        run5.setFontFamily("宋体");
                    }else {
                        run4.setFontFamily("Times");
                        run5.setFontFamily("Times");
                    }
                }
                if(projectPaper.getPaperformContent().getImg1()!=null) {
                    XWPFParagraph paragraph4 = document.createParagraph();
                    XWPFRun run4 = paragraph4.createRun();
                    run4.setText("Table and Figure:");
                    run4.setFontSize(8);
                    run4.setBold(true);
                    XWPFRun run5 = paragraph4.createRun();
                    run5.setFontSize(8);
                    File file=new File(projectPaper.getPaperformContent().getImg1());
                    if(file.exists()) {
                        String picId = document.addPictureData(new FileInputStream(projectPaper.getPaperformContent().getImg1()), XWPFDocument.PICTURE_TYPE_PNG);  
                        (document).createPicture(picId, document.getNextPicNameNumber(XWPFDocument.PICTURE_TYPE_PNG),200,150);  
                        XWPFRun run6 = paragraph4.createRun();
                        run6.setText("Figure 1.");
                        run6.setFontSize(8);
                        run6.setBold(true);
                        XWPFRun run7 = paragraph4.createRun();
                        run7.setText(projectPaper.getPaperformContent().getImg1Title());
                        run7.setFontSize(8);
                    }
                }
                if(projectPaper.getPaperformContent().getImg2()!=null) {
                    XWPFParagraph paragraph4 = document.createParagraph();
                    XWPFRun run5 = paragraph4.createRun();
                    run5.setFontSize(8);
                    File file=new File(projectPaper.getPaperformContent().getImg2());
                    if(file.exists()) {
                        String picId = document.addPictureData(new FileInputStream(projectPaper.getPaperformContent().getImg2()), XWPFDocument.PICTURE_TYPE_PNG);  
                        (document).createPicture(picId, document.getNextPicNameNumber(XWPFDocument.PICTURE_TYPE_PNG),200,150);  
                        XWPFRun run6 = paragraph4.createRun();
                        run6.setText("Figure 2.");
                        run6.setFontSize(8);
                        run6.setBold(true);
                        XWPFRun run7 = paragraph4.createRun();
                        run7.setText(projectPaper.getPaperformContent().getImg2Title());
                        run7.setFontSize(8);
                    }
                }
                File files=new File("/uppaper");
                if(!files.exists()) {
                    files.mkdirs();
                }
                FileOutputStream fout = new FileOutputStream("/uppaper/"+new File(projectPaper.getPaperCode()+".docx"));
                document.write(fout);  
                fout.close();
            }
            File file=new File("/uppaper");
            if(!file.exists()) {
                file.mkdirs();
            }
            craeteZipPath("/uppaper",resp);

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            File file=new File("/uppaper");
            if(file.exists()) {
                file.delete();
            }
        }
    }
    //将html格式的字符串转换为纯文本
    public static String toPlainText(final String html){  
        if (html == null)  
        {  
            return "";  
        }  
        final Document document = Jsoup.parse(html);  
        final OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);  
        document.outputSettings(outputSettings);  
        document.select("br").append("\\n");  
        document.select("p").prepend("\\n");  
        document.select("p").append("\\n");  
        final String newHtml = document.html().replaceAll("\\\\n", "\n");  
        final String plainText = Jsoup.clean(newHtml, "", Whitelist.none(), outputSettings);  
        final String result = StringEscapeUtils.unescapeHtml4(plainText.trim());  
        return result;  
    }

    public static void craeteZipPath(String path,HttpServletResponse response) throws IOException{  

        ZipOutputStream zipOutputStream = null;
        OutputStream output=response.getOutputStream();  
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename="+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".zip");  
        response.setContentType("application/msexcel");  
        zipOutputStream = new ZipOutputStream(output,Charset.forName("GBK"));  
        File[] files = new File(path).listFiles();  
        FileInputStream fileInputStream = null;  
        byte[] buf = new byte[1024];  
        int len = 0;  
        if(files!=null && files.length > 0){  
            for(File excelFile:files){  
                String fileName = excelFile.getName();  
                fileInputStream = new FileInputStream(excelFile);  
                //放入压缩zip包中;  
                zipOutputStream.putNextEntry(new ZipEntry(fileName));  

                //读取文件;  
                while((len=fileInputStream.read(buf)) >0){  
                    zipOutputStream.write(buf, 0, len);  
                }  
                //关闭;  
                zipOutputStream.closeEntry();  
                if(fileInputStream != null){  
                    fileInputStream.close();  
                }  
            }  
        }  

        if(zipOutputStream !=null){  
            zipOutputStream.close();  
        }  
    } 

poi导出为word的样式参考:https://www.cnblogs.com/dayuruozhi/p/6490793.html
压缩为zip参考:https://blog.youkuaiyun.com/hongwangzhang/article/details/50770528

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值