使用poi读取word文档(docx类型),进行数据替换。
另外,为了记录poi设置行间距的api,真是找了好几十分钟才找到啊啊啊啊!!!
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author yyh
*/
public class Test {
public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("要更改的字符", "yes,is,me");
Set<String> strings = map.keySet();
File file = new File("E:\\导入.docx");
FileInputStream in = new FileInputStream(file);
XWPFDocument doc = new XWPFDocument(in);
//替换表格的内容
List<XWPFTable> tables = doc.getTables();
for (XWPFTable table : tables) {
List<XWPFTableRow> rows = table.getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> tableCells = row.getTableCells();
for (XWPFTableCell tableCell : tableCells) {
String text = tableCell.getText();
if (!StringUtils.isEmpty(text) && strings.contains(text)) {
//setText底层是追加,所以要删除删除原来的段落
tableCell.removeParagraph(0);
//设置段落的样式,行间距
XWPFParagraph para = tableCell.addParagraph();
para.setSpacingBetween(1);
//赋值
tableCell.setText(map.get(text));
}
}
}
}
OutputStream out = new FileOutputStream("E:\\导出.docx");
// 输出
doc.write(out);
in.close();
out.close();
}
}