码迷,mamicode.com
首页 > 其他好文 > 详细

poi导出word

时间:2015-08-06 18:10:11      阅读:366      评论:0      收藏:0      [点我收藏+]

标签:

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

  说一个比较实用的方法,插入分节和设置页面第二页开始时就是用的这种方法:先新建一个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

 

poi导出word

标签:

原文地址:http://www.cnblogs.com/xiufengd/p/4708680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!