package com.iuit.test.file;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.wp.usermodel.Paragraph;
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.poi.xwpf.usermodel.XWPFTableRow;
import org.junit.Test;
public class FileTest {
/**
* 文檔模板 將${xxxx}替換
* @throws IOException
*/
@Test
public void test1() throws IOException {
//准備工作,生成docx對象
String templatePath="D:\\tmp\\sample.docx";
InputStream is=new FileInputStream(templatePath);
XWPFDocument docx=new XWPFDocument(is);
//獲取所有的段
List<XWPFParagraph> paragraphs=docx.getParagraphs();
//遍歷所有的段
for(int i=0;i<paragraphs.size();i++) {
//獲取該段所有的文本對象
List<XWPFRun> runs=paragraphs.get(i).getRuns();
for(int j=0;j<runs.size();j++) {
XWPFRun run=runs.get(j);
//假如該文本對象里包含${name},則使用run.setText(str.replace("${name}","fucker"),0)替換
if(run.toString().contains("${name}")) {
String str=run.toString();
run.setText(str.replace("${name}", "fucker"),0);
}
}
}
//輸出到write.docx
OutputStream os=new FileOutputStream("D:\\tmp\\write.docx");
docx.write(os);
is.close();
os.close();
}
/**
* add table
* @author dwg
* 操作表格,增加表格行
*/
@Test
public void test2() throws IOException{
//准備工作,生成docx對象
String templatePath="D:\\tmp\\sample.docx";
InputStream is=new FileInputStream(templatePath);
XWPFDocument docx=new XWPFDocument(is);
//獲取所有的Table
List<XWPFTable> tables=docx.getTables();
//定位到第一個Table
XWPFTable table=tables.get(0);
//Table增加一行
table.createRow();
//定位到新新加的行,一開始只有兩行,一加變成三行,定位為2
XWPFTableRow row=table.getRow(2);
//添加內容
row.getCell(0).setText("1111");
//輸出
OutputStream os=new FileOutputStream("D:\\tmp\\write.docx");
docx.write(os);
is.close();
os.close();
}
/**
*
* 給表格中${xxx}替換為需要的文本
*/
@Test
public void test3() throws IOException {
//准備工作,生成docx對象
String templatePath="D:\\tmp\\sample.docx";
InputStream is=new FileInputStream(templatePath);
XWPFDocument docx=new XWPFDocument(is);
//獲取表格
List<XWPFTable> tables=docx.getTables();
//定位到第一個表格
XWPFTable table=tables.get(0);
//遍歷該表格所有的行
for(int i=0;i<table.getRows().size();i++) {
XWPFTableRow row=table.getRow(i);
//遍歷該行所有的列
for(int j=0;j<row.getTableCells().size();j++) {
XWPFTableCell cell=row.getTableCells().get(j);
//獲取該格子里所有的段
List<XWPFParagraph> paragraphs=cell.getParagraphs();
for(XWPFParagraph p:paragraphs) {
//遍歷該格子里的段
List<XWPFRun> runs=p.getRuns();
for(XWPFRun run:runs) {
//遍歷該段里的所有文本
String str=run.toString();
//如果該段文本包含${like},則替換
if(str.equals("${like}")) {
run.setText("fuck",0);
}
}
}
}
}
//輸出
OutputStream os=new FileOutputStream("D:\\tmp\\write.docx");
docx.write(os);
is.close();
os.close();
}
}