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

 

转载于:https://www.cnblogs.com/AardWolf/p/11268874.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值