POI 写出word文档实例

一、Service

package com.example.demo.service;

import java.io.*;
import java.math.BigInteger;
import java.util.*;

import org.apache.poi.xwpf.usermodel.*;
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;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import com.example.demo.entity.StudentCertificate;

public class WPSService {
    
    public XWPFDocument writeWord(List<StudentCertificate> data) throws Exception {

        XWPFDocument doc = new XWPFDocument();
                //设置页边距
        CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();  
        CTPageMar pageMar = sectPr.addNewPgMar();  
        pageMar.setLeft(BigInteger.valueOf(720L));  
        pageMar.setTop(BigInteger.valueOf(720L));  
        pageMar.setRight(BigInteger.valueOf(720L));  
        pageMar.setBottom(BigInteger.valueOf(720L));
        
        int size = data.size();
        int page = size/4+1;
        int k = 0;
        int titleDivide = 17;
        System.out.println("===> 共有:"+size+" 条数据\n===> 生成页数:"+page);
        
        for(int p = 0; p < page; p++) {
            XWPFTable table= doc.createTable(2,2);
            List<XWPFTableRow> list = table.getRows();//获取行的集合
            for(XWPFTableRow r : list)
                r.setHeight(6975);
            //给table增加一个属性设置,用于设置列宽
            CTTblPr cp = table.getCTTbl().addNewTblPr();
            CTTblWidth cw = cp.addNewTblW();
            cw.setW(BigInteger.valueOf(10800));//8320));
            cw.setType(STTblWidth.DXA);
            //隐藏表格框
            table.getCTTbl().getTblPr().unsetTblBorders();
     
            for(XWPFTableRow i : list) {
                if(k == size)
                    break;
                for(XWPFTableCell j : i.getTableCells()) {
                    if(k == size)
                        break;
                    StudentCertificate sc = data.get(k++);
                    XWPFParagraph xp;
                    CTFonts font;
                    //标题
                    xp = j.addParagraph();
                    XWPFRun title = xp.createRun();
                    font = title.getCTR().addNewRPr().addNewRFonts();
                    font.setEastAsia("仿宋");
                    font.setAscii("仿宋");
                    title.setText(sc.getTitle().substring(0, titleDivide));
                    title.addBreak();
                    title.setText(sc.getTitle().substring(titleDivide));
                    title.setFontSize(22);
                    title.setColor("00B0F0");
                    title.setBold(true);
                    xp.setVerticalAlignment(TextAlignment.CENTER);
                    xp.setAlignment(ParagraphAlignment.CENTER);

                    xp = j.addParagraph();
                    //区域
                    xp = j.addParagraph();
                    XWPFRun area = xp.createRun();
                    area.setText(sc.getArea());
                    font = area.getCTR().addNewRPr().addNewRFonts();
                    font.setEastAsia("仿宋");
                    font.setAscii("仿宋");
                    area.setFontSize(14);
                    area.setBold(true);
                    xp.setVerticalAlignment(TextAlignment.CENTER);
                    xp.setAlignment(ParagraphAlignment.CENTER);

                    xp = j.addParagraph();
                    FileInputStream in = new FileInputStream(sc.getImage());
                    byte[] ba = new byte[in.available()];
                    in.read(ba);
                    doc.addPictureData(ba, XWPFDocument.PICTURE_TYPE_JPEG);
                    createPicture(doc, doc.getAllPictures().size() - 1, 140, 140, xp);
                    xp.setVerticalAlignment(TextAlignment.CENTER);
                    xp.setAlignment(ParagraphAlignment.CENTER);
                    xp = j.addParagraph();
                    
                    //姓名
                    xp = j.addParagraph();
                    XWPFRun name = xp.createRun();
                    name.setText("    姓名: "+sc.getName());
                    font = name.getCTR().addNewRPr().addNewRFonts();
                    font.setEastAsia("黑体");
                    font.setAscii("黑体");
                    name.setFontSize(12);
                    name.setBold(true);
                    
                    //学校
                    xp = j.addParagraph();
                    XWPFRun school = xp.createRun();
                    school.setText("    学校: "+sc.getSchool());
                    font = school.getCTR().addNewRPr().addNewRFonts();
                    font.setEastAsia("黑体");
                    font.setAscii("黑体");
                    school.setFontSize(12);
                    school.setBold(true);
                    
                    //ID
                    xp = j.addParagraph();
                    XWPFRun id = xp.createRun();
                    id.setText("    ID号: "+sc.getId());
                    font = id.getCTR().addNewRPr().addNewRFonts();
                    font.setEastAsia("黑体");
                    font.setAscii("黑体");
                    id.setFontSize(12);
                    id.setBold(true);
                    
                    //举办方
                    xp = j.addParagraph();
                    XWPFRun cont = xp.createRun();
                    cont.setText("      "+sc.getContractor());
                    font = cont.getCTR().addNewRPr().addNewRFonts();
                    font.setEastAsia("黑体");
                    font.setAscii("黑体");
                    cont.setFontSize(12);
                    cont.setBold(true);
                }
            }
        }
        return doc;
    }
    
    
    /**
     * @param id
     * @param doc 文档
     * @param width 宽
     * @param height 高
     * @param paragraph 段落
     */
    public void createPicture(XWPFDocument doc, int id, int width, int height,
            XWPFParagraph paragraph) {
        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
        String blipId = doc.getAllPictures().get(id).getPackageRelationship()
                .getId();
        CTInline inline = paragraph.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>";
 
        inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        try {
            xmlToken = XmlToken.Factory.parse(picXml);
        } catch (XmlException xe) {
            xe.printStackTrace();
        }
        inline.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("图片名称");
        docPr.setDescr("描述信息");
    }
}
    
View Code

二、Test

package com.example.demo.web;

import java.io.FileOutputStream;
import java.util.*;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.example.demo.SpringDemo2Application;
import com.example.demo.entity.StudentCertificate;
import com.example.demo.service.WPSService;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringDemo2Application.class)
public class WPSTest {
    WPSService ws = new WPSService();
    
    @Test
    public void test01() {
        try {
            // 假数据模型
            StudentCertificate sc = new StudentCertificate();
            sc.setTitle("FCS HYZ20HYZ1901 C++编程培训");
            sc.setArea("惠安第一中学");
            sc.setImage("E:\\我的图片\\test.jpg");
            sc.setName("张三");
            sc.setSchool("北京大学");
            sc.setId("111111");
            sc.setContractor("福建省计算机学会普及工作委员会");
            
            List<StudentCertificate> list = new ArrayList<StudentCertificate>();
            
            int n = 7;
            while(n-- != 0)
                list.add(sc);
            
            XWPFDocument doc = ws.writeWord(list);
    
            FileOutputStream out = new FileOutputStream("C:\\Users\\13497\\Desktop\\test.docx");
            doc.write(out);
            out.close();
            System.out.println("====> 文件创建成功!");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
View Code

三、pom.xml

<!-- POI 3.9 的支持 兼容 1.1 schemas -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>ooxml-schemas</artifactId>
    <version>1.1</version>
</dependency>
View Code

 

posted @ 2019-07-30 11:15  MoonTwilight  阅读(369)  评论(0编辑  收藏  举报