一、内容概要
1,下载jacob.jar,将jacob自带的DLL放入SYSTEM32中,确保电脑装了WORD程序;
2,方法是:FILE[]遍历特定文件夹,JACOB读取WORD中表格的内容,封装成arraylist,然后批量插入数据库
二、核心码
1,words.java;遍历文件夹,取出word表格中的内容到arraylist
package main.java.utils;
import java.io.File;//用于遍历文件夹下所有文件
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import main.java.Cus;//一个POJO普通类
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
//import test.wordBean;
public class Words {
// word文档
private static Dispatch doc;
// word运行程序对象
private ActiveXComponent word;
// 所有word文档集合
private Dispatch documents;
// 选定的范围或插入点
private Dispatch selection;
private boolean saveOnExit = true;
private ArrayList alist=null;
private ArrayList al1=null;
private Cus cus=null;
public Words() throws Exception {
if (word == null) {
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(false)); // 不可见打开word
word.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
}
if (documents == null)
documents = word.getProperty("Documents").toDispatch();
}
//创建一个新的word文档
public void createNewDocument() {
doc = Dispatch.call(documents, "Add").toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
//打开一个已存在的文档
public void openDocument(String docPath) {
createNewDocument();
doc = Dispatch.call(documents, "Open", docPath).toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
//获得指定的单元格里数据
public String getTxtFromCell(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;
}
//关闭
public void cl