Jacob 获取段落内容和表格内容
直接上代码
public class JacobTest {
public static void main(String[] args) {
String source = "C:\\Users\\demon\\Downloads\\合同1 (1).docx";
ActiveXComponent axc = new ActiveXComponent("KWPS.Application");
axc.setProperty("Visible", false);
Dispatch dispatch = axc.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(dispatch, "Open", source).toDispatch();
//获取段落
Dispatch paragraphs = Dispatch.get(doc, "Paragraphs").toDispatch();
int count = Dispatch.get(paragraphs, "Count").getInt();//段落数量
System.out.println("段落的数量为:" + count);
for (int i = 0; i <= count - 1; i++) {
Dispatch paragraph = Dispatch.call(paragraphs, "Item", new Variant(i + 1)).toDispatch();
// level 大于4 的都是内容,小于4 的是大纲
// int level = Dispatch.get(paragraph, "OutlineLevel").getInt();
Dispatch paragraphRange = Dispatch.get(paragraph, "Range").toDispatch();
String text = Dispatch.get(paragraphRange, "Text").toString();
System.out.println("这是第" + (i + 1) + "段内容");
System.out.println(text);
}
// 获取所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 获取表格数目
int tablesCount = Dispatch.get(tables, "Count").getInt();
System.out.println("文档中共有" + tablesCount + "个表格");
for (int i = 1; i <= tablesCount; i++) {
// 获取第i个表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(i)).toDispatch();
// 获取该表格所有行
Dispatch rows = Dispatch.call(table, "Rows").toDispatch();
// 获取该表格所有列
Dispatch columns = Dispatch.call(table, "Columns").toDispatch();
// 获取该表格行数
int rowsCount = Dispatch.get(rows, "Count").getInt();
// 获取该表格列数
int columnsCount = Dispatch.get(columns, "Count").getInt();
for (int j = 1; j <= rowsCount; j++) {
for (int k = 1; k <= columnsCount; k++) {
Dispatch cell = Dispatch.call(table, "Cell", new Variant(j), new Variant(k)).toDispatch();
Dispatch Range = Dispatch.get(cell, "Range").toDispatch();
String text = Dispatch.get(Range, "Text").getString();
//去掉最后的回车符;
text = text.substring(0, text.length() - 2);
System.out.println("单元格中的内容:" + text);
}
}
}
axc.invoke("Quit", 0);
dispatch.safeRelease();
}
public String getTxtFromCell(Dispatch doc, int tableIndex, int cellRowIdx, int cellColIdx) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();
Dispatch rows = Dispatch.call(table, "Rows").toDispatch();
Dispatch columns = Dispatch.call(table, "Columns").toDispatch();
Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx), new Variant(cellColIdx)).toDispatch();
Dispatch Range = Dispatch.get(cell, "Range").toDispatch();
System.out.println(Dispatch.get(Range, "Text").toString());
Dispatch.call(cell, "Select");
String ret = "";
// ret = Dispatch.get(selection, "Text").toString();
ret = ret.substring(0, ret.length() - 2); // 去掉最后的回车符;
return ret;
}
}