poi导出word

  本测试文档为自己找资料写的一个代码,实现了我所需要的功能,包括页眉页脚,段落剧中,创建表格,表格样式等等。

  说一个比较实用的方法,插入分节和设置页面第二页开始时就是用的这种方法:先新建一个docx文件,编辑好自己需要的格式,包括页眉页脚,分页分节等,然后保存,重命名成zip压缩文件,解压后就会发现很多xml文件,这就是word的底层,可以从相关xml里面查找相应的功能。

  目前仍存在一个问题就是空格的下滑先不显示,具体解决后续添加

package poi;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.xmlbeans.impl.xb.xmlschema.SpaceAttribute;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageNumber;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblBorders;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

public class WordDemo {
  //生成测试报告
  public static boolean createnewword(){
    XWPFDocument doc = new XWPFDocument();
    firstpage(doc);
    secondpage(doc);
    exchange(doc);
    export(doc);
    return true;
  }
  public static void main(String[] arg){
    XWPFDocument doc = new XWPFDocument();
    firstpage(doc);
    secondpage(doc);
    exchange(doc);
    export(doc);
  }
  /**
  * @Description: 得到XWPFRun的CTRPr
  */
  public static CTRPr getRunCTRPr(XWPFParagraph p, XWPFRun pRun) {
    CTRPr pRpr = null;
    if (pRun.getCTR() != null) {
      pRpr = pRun.getCTR().getRPr();
      if (pRpr == null) {
        pRpr = pRun.getCTR().addNewRPr();
      }
    } else {
      pRpr = p.getCTP().addNewR().addNewRPr();
    }
    return pRpr;
  }
  //页眉
  public static void simpleDateHeader(XWPFDocument document) throws Exception {
    CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
    CTPageNumber pageNum = sectPr.addNewPgNumType();
    pageNum.setStart(BigInteger.ONE);

    CTP ctp = CTP.Factory.newInstance();
    XWPFParagraph codePara = new XWPFParagraph(ctp, document); 

    XWPFRun r1 = null;
    CTFldChar fldChar = null;
    CTRPr rpr =null;
    CTFonts fonts=null;
    CTText ctText =null;

    r1 = codePara.createRun();
    setfont(r1,9,"宋体","编号: 第"); 

    r1 = codePara.createRun();
    fldChar = r1.getCTR().addNewFldChar();
    fldChar.setFldCharType(STFldCharType.Enum.forString("begin")); 

    r1 = codePara.createRun();
    ctText = r1.getCTR().addNewInstrText();
    ctText.setStringValue("PAGE \\* MERGEFORMAT");
    ctText.setSpace(SpaceAttribute.Space.Enum.forString("preserve"));
    r1.setFontSize(9);
    rpr = r1.getCTR().isSetRPr() ? r1.getCTR().getRPr() : r1.getCTR().addNewRPr();
    fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();
    fonts.setAscii("宋体");
    fonts.setEastAsia("宋体");
    fonts.setHAnsi("宋体"); 

    fldChar = r1.getCTR().addNewFldChar();
    fldChar.setFldCharType(STFldCharType.Enum.forString("end")); 

    r1 = codePara.createRun();
    setfont(r1,9,"宋体"," 页 共");
    r1 = codePara.createRun();
    fldChar = r1.getCTR().addNewFldChar();
    fldChar.setFldCharType(STFldCharType.Enum.forString("begin")); 

    r1 = codePara.createRun();
    ctText = r1.getCTR().addNewInstrText();
    ctText.setStringValue("SECTIONPAGES \\* MERGEFORMAT");
    ctText.setSpace(SpaceAttribute.Space.Enum.forString("preserve"));
    r1.setFontSize(9);
    rpr = r1.getCTR().isSetRPr() ? r1.getCTR().getRPr() : r1.getCTR().addNewRPr();
    fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();
    fonts.setAscii("宋体");
    fonts.setEastAsia("宋体");
    fonts.setHAnsi("宋体");
    fldChar = r1.getCTR().addNewFldChar();
    fldChar.setFldCharType(STFldCharType.Enum.forString("end"));
    setfont(r1,9,"宋体"," 页");
    codePara.setAlignment(ParagraphAlignment.CENTER);
    codePara.setVerticalAlignment(TextAlignment.CENTER);
    XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
    newparagraphs[0] = codePara;
    XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
    headerFooterPolicy.createHeader(STHdrFtr.DEFAULT, newparagraphs);
  }
  //页脚
  public static void simpleNumberFooter(XWPFDocument document) throws Exception {
    CTP ctp = CTP.Factory.newInstance();
    XWPFParagraph codePara = new XWPFParagraph(ctp, document);
    codePara.setAlignment(ParagraphAlignment.CENTER);

    XWPFRun r1 = codePara.createRun();
    setfont(r1,11,"宋体","这里是页脚");

    XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
    newparagraphs[0] = codePara;
    CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
    XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
    headerFooterPolicy.createFooter(STHdrFtr.DEFAULT, newparagraphs);
  }
  public static CTPPr getParagraphCTPPr(XWPFParagraph p) {
    CTPPr pPPr = null;
    if (p.getCTP() != null) {
      if (p.getCTP().getPPr() != null) {
        pPPr = p.getCTP().getPPr();
      } else {
        pPPr = p.getCTP().addNewPPr();
      }
    }
   return pPPr;
  }
  //设置段落格式
  public static void setpage(XWPFParagraph page,ParagraphAlignment align,int num,int Spacing){
    page.setAlignment(align);
    if(Spacing==0){
      page.setSpacingBeforeLines(50);
      page.setSpacingAfterLines(50);
    }else{
      page.setSpacingBeforeLines(Spacing);
      page.setSpacingAfterLines(Spacing);
    }
    if(num!=-1){
      page.setIndentationLeft(num);
    }

    CTPPr pPpr = null;
    pPpr = page.getCTP().getPPr();
    if (pPpr == null) {
      pPpr = page.getCTP().addNewPPr();
    }
    CTShd shd = pPpr.isSetShd() ? pPpr.getShd() : pPpr.addNewShd();
    shd.setVal(STShd.Enum.forInt(100));
  }
  public static void setfont(XWPFRun run,int font,String family,String text){
    run.setFontSize(font);
    run.setFontFamily(family);
    run.setText(text);
  }
  //封面
  public static void firstpage(XWPFDocument doc){
    //头
    XWPFParagraph page = doc.createParagraph();
    XWPFRun run = page.createRun();
    run.setBold(true);
    setfont(run,14,"宋体","编号:");
    //空行
    page = doc.createParagraph();
    page.setAlignment(ParagraphAlignment.CENTER);
    run = page.createRun();
    setfont(run,36,"宋体","");
    run.addBreak();
    //名
    run = page.createRun();
    run.setBold(true);
    setfont(run,36,"宋体","报 告");
    //空行
    page = doc.createParagraph();
    run = page.createRun();
    setfont(run,14,"宋体","");
    run.addBreak();run.addBreak();run.addBreak();run.addBreak();
    //单位
    page = doc.createParagraph();
    setpage(page,ParagraphAlignment.BOTH,2000,100);
    run = page.createRun();
    setfont(run,14,"宋体","单位:");
    run = page.createRun();
    run.setUnderline(UnderlinePatterns.SINGLE);
    //类别
    page = doc.createParagraph();
    setpage(page,ParagraphAlignment.BOTH,2000,100);
    run = page.createRun();
    setfont(run,14,"宋体","报告:");
    run = page.createRun();
    run.setUnderline(UnderlinePatterns.SINGLE);
    //空行
    page = doc.createParagraph();
    run = page.createRun();
    setfont(run,14,"宋体","");
    run.addBreak();
    run.addBreak();
    //尾
    page = doc.createParagraph();
    setpage(page,ParagraphAlignment.BOTH,1800,100);
    run = page.createRun();
    setfont(run,14,"宋体","检测单位:XXXXXXXXXXXXXXXXXXXX");
    page = doc.createParagraph();
    setpage(page,ParagraphAlignment.BOTH,1800,100);
    run = page.createRun();
    setfont(run,14,"宋体","日期: 年 月 日");
    page = doc.createParagraph();
    if(page.getCTP().getPPr()==null){
      page.getCTP().addNewPPr().addNewSectPr();
    }else{
      page.getCTP().getPPr().addNewSectPr();
    }
  }
  //内容页
  public static void secondpage(XWPFDocument doc){
    XWPFParagraph page = null;
    XWPFRun run = null;
    try {
      simpleDateHeader(doc);
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      simpleNumberFooter(doc);
    } catch (Exception e) {
      e.printStackTrace();
    }
    page = doc.createParagraph();
    setpage(page,ParagraphAlignment.LEFT,0,0);
    run = page.createRun();
    run.setBold(true);
    setfont(run,11,"宋体","标题");
    run.addBreak();

    run = page.createRun();
    setfont(run,11,"宋体","首行");
    run.addBreak();run.addBreak();

    run = page.createRun();
    setfont(run,11,"宋体","提示");
    run.addBreak();

    run = page.createRun();
    run.setBold(true);
    run = page.createRun();
    setfont(run,11,"宋体","XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    run.addBreak();

    createTableCB(doc);
    page.setPageBreak(true);
  }
  //5列
  public static void createTableCB(XWPFDocument doc){
    XWPFTable tb = doc.createTable(5,2);
    settabcelCB(tb,0,"XXXXXXXX","XXXXXXXX");
    settabcelCB(tb,1,"XXXXXXXX","XXXXXXXX");
    settabcelCB(tb,2,"XXXXXXXX","XXXXXXXX");
    settabcelCB(tb,3,"XXXXXXXX","XXXXXXXX");
    settabcelCB(tb,4,"XXXXXXXX","XXXXXXXX");
  }
  //2列
  public static void settabcelCB(XWPFTable tb,int row,String text1,String text2){
    XWPFParagraph p1 = tb.getRow(row).getCell(0).getParagraphs().get(0);
    p1.setAlignment(ParagraphAlignment.CENTER);
    XWPFRun r1 = p1.createRun();
    setfont(r1,11,"宋体",text1);

    p1 = tb.getRow(row).getCell(1).getParagraphs().get(0);
    p1.setAlignment(ParagraphAlignment.CENTER);
    r1 = p1.createRun();
    setfont(r1,11,"宋体",text2);
  }
  //横向合并单元格
  public static void mergeCellsHorizontal(XWPFTable table, int row, int fromCell,int toCell){
    for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
      XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
      if (cellIndex == fromCell) {
        getCellCTTcPr(cell).addNewHMerge().setVal(STMerge.RESTART);
      } else {
        getCellCTTcPr(cell).addNewHMerge().setVal(STMerge.CONTINUE);
      }
    }
  }
  //纵向合并单元格
  public static void mergeCellsVertically(XWPFTable table, int col, int fromRow,int toRow) {
    for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
      XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
      if (rowIndex == fromRow) {
        getCellCTTcPr(cell).addNewVMerge().setVal(STMerge.RESTART);
      } else {
        getCellCTTcPr(cell).addNewVMerge().setVal(STMerge.CONTINUE);
      }
    }
  }
  public static CTTcPr getCellCTTcPr(XWPFTableCell cell) {
    CTTc cttc = cell.getCTTc();
    CTTcPr tcPr = cttc.isSetTcPr() ? cttc.getTcPr() : cttc.addNewTcPr();
    return tcPr;
  }
  //导出
  public static void export(XWPFDocument doc){
    //导出
    FileOutputStream out = null;
    try {
      out = new FileOutputStream("F:/报告.docx");
      doc.write(out);
      out.flush();
      out.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  //统一设置表格样式和宽度
  public static void exchange(XWPFDocument doc){
    List<XWPFTable> list = doc.getTables();
    for (XWPFTable xwpfTable : list) {
      CTTblBorders border = CTTblBorders.Factory.newInstance();
      CTBorder left = border.isSetLeft()?border.getLeft():CTBorder.Factory.newInstance();
      left.setSz(BigInteger.ONE);
      CTBorder right = border.isSetRight()?border.getRight():CTBorder.Factory.newInstance();
      right.setSz(BigInteger.ONE);
      CTBorder bottom = border.isSetBottom()?border.getBottom():CTBorder.Factory.newInstance();
      bottom.setSz(BigInteger.ONE);
      CTBorder top = border.isSetTop()?border.getTop():CTBorder.Factory.newInstance();
      top.setSz(BigInteger.ONE);
      //内部横线
      CTBorder insideH = border.isSetInsideH()?border.getInsideH():CTBorder.Factory.newInstance();
      insideH.setSz(BigInteger.ONE);
      //内部竖线
      CTBorder insideV = border.isSetInsideV()?border.getInsideV():CTBorder.Factory.newInstance();
      insideV.setSz(BigInteger.ONE);

      insideH.setVal(STBorder.Enum.forInt(STBorder.INT_PENCILS));
      insideV.setVal(STBorder.Enum.forInt(STBorder.INT_PENCILS));
      top.setVal(STBorder.Enum.forInt(STBorder.INT_PENCILS));
      bottom.setVal(STBorder.Enum.forInt(STBorder.INT_PENCILS));
      left.setVal(STBorder.Enum.forInt(STBorder.INT_NONE));
      right.setVal(STBorder.Enum.forInt(STBorder.INT_NONE));

      border.setLeft(left);
      border.setRight(right);
      border.setBottom(bottom);
      border.setTop(top);
      border.setInsideH(insideH);
      border.setInsideV(insideV);

      xwpfTable.getCTTbl().getTblPr().setTblBorders(border);
      //表格属性
      CTTbl ttbl = xwpfTable.getCTTbl();
      CTTblPr tablePr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
      //表格宽度
      CTTblWidth tblWidth = tablePr.isSetTblW()?tablePr.getTblW():tablePr.addNewTblW();
      tblWidth.setW(BigInteger.valueOf(8500));
      //设置表格宽度为非自动
      tblWidth.setType(STTblWidth.DXA);

      CTJc jc = tablePr.isSetJc()?tablePr.getJc():tablePr.addNewJc();
      jc.setVal(STJc.Enum.forInt(ParagraphAlignment.CENTER.getValue()));
    }
  }
}

参考文档:http://tool.oschina.net/apidocs/apidoc?api=apache-POI

     http://www.tuicool.com/articles/Nr2IV3q

时间: 2024-11-06 03:42:51

poi导出word的相关文章

poi导出word时设置兼容性

接上一篇poi导出word http://www.cnblogs.com/xiufengd/p/4708680.html. public static void setAuto(XWPFDocument doc) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{ List<POIXMLDocumentPart> list = doc.getRelat

使用POI导出Word(含表格)的实现方式及操作Word的工具类

转载请注明出处:https://www.cnblogs.com/sun-flower1314/p/10128796.html 本篇是关于利用Apache 的POI导出Word的实现步骤.采用XWPFDocument导出Word,结构和样式完全由代码控制,操作起来还是非常的不太方便,只能够创建简单的word,不能设置样式,功能太少.但在这里还是实现一下,毕竟做过. 首先声明一些基本概念: XWPFDocument代表一个docx文档,其可以用来读docx文档,也可以用来写docx文档 XWPFPa

poi导出word模板项目实例(一个文件)

在页面上填写值,然后导出到word模板中,并把页面上的值带到模板中,也就是导出word文档,提前有word 的模板形式, 1.jsp 页面   <table class="formTable"> <TR> <TD class="label">会议地点</TD> <TD class="content"> <INPUT id="meetingSite" type=&

poi导出word表格跨行

DataCommon.java package com.ksource.pwlp.model.statistic; public class DataCommon { private Long id; private String name; private String otherName; private String dataName; private String otherDataName; private int value; private float otherValue; pr

poi导出word、excel

在实际的项目开发中,经常会有一些涉及到导入导出的文档的功能.apache开源项目之一poi对此有很好的支持,对之前的使用做一些简要的总结. 1,导入jar 为了保证对格式的兼容性,在项目的pom.xml添加这三个jar: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.13</version> &l

poi 导出word,导出表格(复杂表格合并行列)解决方法

如下图:一个table表格,需要作为表格插入到word中: 1.首先对表格做拆分处理 代码如下: private String simplifyTable(String tableContent) { if(StringUtils.isEmpty(tableContent)) return null; Document tableDoc = Jsoup.parse(tableContent); Elements trElements = tableDoc.getElementsByTag("tr

poi 导出word,导出图片解决方法

    /**  * 写入图片  * @param document  * @param picName  * @param width  * @param height  * @param alignment   */ private void WriteImage(CustomXWPFDocument document, String picName, int width, int height, ParagraphAlignment alignment) { try { CustomXWP

iText导出word入门

最近一个项目需要导出word文档,网上了解了一下,发现poi导出excel比较好,但是导出word就力不从心了,大家都比较推荐iText,于是试了试,感觉还不错. 我用的是2.1.7版本. 1. 使用maven导入依赖 <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.7</version> <

POI导出EXCEL经典实现(转)

http://www.cnblogs.com/xwdreamer/archive/2011/07/20/2296975.html 1.Apache POI简介 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能. .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 POI 的功能. 2.POI结构 HSSF - 提供读写Microsoft Excel XLS格式档案的功能.XS