1 word文档解析
获取段落和表格中所有单元格信息
file.getInputStream();
InputStream fis = file.getInputStream();
XWPFDocument doc = new XWPFDocument(fis);
WesInfoCollection wes = new WesInfoCollection();
//表头标题
String number = null;
List<XWPFParagraph> paragraphss = doc.getParagraphs();
if (paragraphss.size() >= 3){
String text = paragraphss.get(2).getText();
number = text.replace("编号", "").trim();
if (StringUtils.hasText(number)) {
wes.setNumber(number);
} else {
throw new BizRuntimeException("编号为空");
}
}
if (!ObjectUtils.isEmpty(info)){
throw new BizRuntimeException("该编号数据已存在");
}
//表格内容
List<XWPFTableCell> cellList = new ArrayList();
List<XWPFTable> tables = doc.getTables();
for (XWPFTable table : tables) {
List<XWPFTableRow> rows = table.getRows();
if (rows.size() == 21){
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
cellList.add(cell);
}
}
}else {
throw new BizRuntimeException("word结构行数有变");
}
}
根据单元格中的信息进行解析
for (int i = 0; i < sampleTypeArr.length; i++){
if (sampleTypeArr[i].contains("☑")){
proSampleType.append("," + i);
}
}
if (StringUtils.hasText(proSampleType)){
proSampleType.deleteCharAt(0);
}
String pst = proSampleType.toString();
wes.setProSampleType(pst);
if (pst.contains("4")){
String trim = sampleTypeArr[5].replace("☑", "").replace("□", "").trim();
wes.setProSampleDna(StringUtils.hasText(trim) ? trim : "");
}
if (pst.contains("5") && sampleTypeArr.length >= 6){
String trim = sampleTypeArr[6].replace("☑", "").replace("□", "").trim();
wes.setProSampleOther(StringUtils.hasText(trim) ? trim : "");
}
2.修改word文档中的内容
1.修改段落中的内容,根据字符去匹配修改即可
XWPFDocument doc = new XWPFDocument(fileInputStream); List<XWPFParagraph> paragraphss = doc.getParagraphs(); for (XWPFParagraph paragraph : paragraphss) { for (XWPFRun run : paragraph.getRuns()) { if (run.text().contains("«proband_name»")){ String text = run.text().replace("«proband_name»", "张三"); run.setText(text); } System.out.println(run.text()); } }
2.修改表格中单元格内容,此处直接使用cell.setText()方法只能进行单元格内容追加。
在网上搜到了一个可行的修改单元格的方法
List<XWPFTable> tables = doc.getTables(); for (XWPFTable table : tables) { List<XWPFTableRow> rows = table.getRows(); for (XWPFTableRow row : rows) { List<XWPFTableCell> cells = row.getTableCells(); for (XWPFTableCell cell : cells) { if (cell.getText().contains("«proband_name»")){ String text = cell.getText().replace("«proband_name»", "张三"); cell.removeParagraph(0); XWPFParagraph newParagraph = cell.addParagraph(); XWPFRun newRun = newParagraph.createRun(); newRun.setText(text); } System.out.println(cell.getText()); } } }