如果文档包含图像,段落和表格,如何以相同的顺序读取docx文件。
答案 0 :(得分:0)
使用 Apache POI 框架可以阅读和操作.docx
个文件。
您需要XWPF
个库和ooxml-schemas
才能执行此操作。
以下是如何阅读Microsoft Word文件的示例:
public void readDocxFile() throws IOException
{
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template.docx");
XWPFDocument doc = new XWPFDocument(inputStream);
//Paragraphs
List<XWPFParagraph> paragraphs = doc.getParagraphs();
XWPFParagraph paragraph = paragraphs.get(1);
//Runs
List<XWPFRun> runs = paragraph.getRuns();
XWPFRun run = runs.get(1);
run.setText("Some text");
run.setFontSize(12);
run.setBold(true);
//etc.
//Tables
List<XWPFTable> tables = doc.getTables();
XWPFTable table = tables.get(1);
//Rows
List<XWPFTableRow> rows = table.getRows();
XWPFTableRow row = rows.get(1);
//Cells
List<XWPFTableCell> cells = row.getTableCells();
XWPFTableCell cell = cells.get(1);
cell.setText("Some text");
cell.setParagraph(paragraph);
//etc.
}
您还可以创建自己的段落,运行,表格等。这是使用XWPF的第一步的好教程:Apache POI - XWPF Tutorial
对于图片,请尝试使用.getData()
读取字节数组,或者根据Apache POI Documentation使用InputStream,例如getPackagePart().getInputStream()
之后,将您的字节数组转换为图像 - 这tutorial似乎很有用: