java使用POI读写Word
/**
* 填充内容
*/
private void writerRport () {
String filePathEncoding = this.getClass().getClassLoader().getResource("report/测试报告模板V1.0.docx").getPath();
try{
String filePath = URLDecoder.decode(filePathEncoding,"utf-8");
FileInputStream is = new FileInputStream(filePath);
XWPFDocument document = new XWPFDocument(is);
List<XWPFParagraph> paragraphs = document.getParagraphs();
for(int i=0; i<paragraphs.size();i++){
XWPFParagraph paragraph = paragraphs.get(i);
String paragraphText = paragraph.getParagraphText();
if(paragraphText.equals("附件1")){
XmlCursor xmlCursor = paragraph.getCTP().newCursor();
XWPFParagraph newPara = document.insertNewParagraph(xmlCursor);
newPara.setAlignment(ParagraphAlignment.BOTH);//两端对齐
newPara.setIndentationFirstLine(480);//首行缩进24磅
XWPFRun newParaRun = newPara.createRun();
newParaRun.setText("这是新插入的段落!");
newParaRun.setFontFamily("宋体");
newParaRun.setFontSize(12);
newParaRun.setBold(false);
//插入表格
XmlCursor cursor= paragraph.getCTP().newCursor();
XWPFTable table = document.insertNewTbl(cursor);
XWPFTableRow row_0 = table.getRow(0);
row_0.getCell(0).setText("姓名");
row_0.addNewTableCell().setText("年龄");
XWPFTableRow row_1 = table.createRow();
row_1.getCell(0).setText("隔壁老王");
row_1.getCell(1).setText("48");
setTableLocation(table,"center");
setCellLocation(table,"CENTER","center");
break;
}
}
FileOutputStream fos = new FileOutputStream("C:\\zhangcong\\test\\功率半导体器件静态性能测试报告模板V1.0.docx");
document.write(fos);
fos.close();
//创建文档对象
// Document doc = new Document(filePath);
// //添加一个节
// Section section = doc.addSection();
// //添加一个表格
// Table table = section.addTable(true);
// table.resetCells(7, 2);
//保存结果文档
// doc.saveToFile("合并结果.docx", FileFormat.Docx_2013);
}catch (Exception e){
System.out.println(e);
}
}
/**
* 设置单元格水平位置和垂直位置
*
* @param xwpfTable
* @param verticalLoction 单元格中内容垂直上TOP,下BOTTOM,居中CENTER,BOTH两端对齐
* @param horizontalLocation 单元格中内容水平居中center,left居左,right居右,both两端对齐
*/
private void setCellLocation(XWPFTable xwpfTable, String verticalLoction, String horizontalLocation) {
List<XWPFTableRow> rows = xwpfTable.getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
CTTc cttc = cell.getCTTc();
CTP ctp = cttc.getPList().get(0);
CTPPr ctppr = ctp.getPPr();
if (ctppr == null) {
ctppr = ctp.addNewPPr();
}
CTJc ctjc = ctppr.getJc();
if (ctjc == null) {
ctjc = ctppr.addNewJc();
}
ctjc.setVal(STJc.Enum.forString(horizontalLocation)); //水平居中
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf(verticalLoction));//垂直居中
}
}
}
/**
* 设置表格位置
*
* @param xwpfTable
* @param location 整个表格居中center,left居左,right居右,both两端对齐
*/
private void setTableLocation(XWPFTable xwpfTable, String location) {
CTTbl cttbl = xwpfTable.getCTTbl();
CTTblPr tblpr = cttbl.getTblPr() == null ? cttbl.addNewTblPr() : cttbl.getTblPr();
CTJc cTJc = tblpr.addNewJc();
cTJc.setVal(STJc.Enum.forString(location));
}