一、内容概要
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<Cus> 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 closeDocumentWithoutSave() { if (doc != null) { Dispatch.call(doc, "Close", new Variant(false)); doc = null; } } //关闭全部应用 public void close() { //closeDocument(); if (word != null) { Dispatch.call(word, "Quit"); word = null; } selection = null; documents = null; } //遍历文件夹下的所有文件路径 public ArrayList getFilePath(File filedir) throws Exception{ File[] file = filedir.listFiles(); alist=new ArrayList(); for(int i=0; i<file.length; i++){ //获取绝对路径 String filepath=file[i].getAbsolutePath(); // System.out.println(file[i].getAbsolutePath()); alist.add(filepath); // System.out.println(alist.get(i)); if(file[i].isDirectory()){ try{ getFilePath(file[i]); }catch(Exception e){} } } return alist; } //遍历文件夹下的所有文件名 public ArrayList getFileName(File filedir) throws Exception{ alist=new ArrayList(); File[] file = filedir.listFiles(); for(int i=0; i<file.length; i++){ //获取文件名 String filename=file[i].getName().substring(0, file[i].getName().indexOf(".")); alist.add(filename); // System.out.println(alist.get(i)); if(file[i].isDirectory()){ try{ getFileName(file[i]); }catch(Exception e){} } } return alist; } //获取文件夹下文件数量 public int getFileCount(File filedir) throws Exception{ File[] file = filedir.listFiles(); int filecount=file.length; return filecount; } //获取表格中的所有有效内容 public ArrayList<Cus> getFileContent() throws Exception{ File myfiledir = new File("C:\\list"); File[] file = myfiledir.listFiles(); al1=new ArrayList<Cus>(); cus=new Cus(); for (int i = 0; i < file.length; i++) { System.out.println(file.length); if (!file[i].isHidden()) { String filepaths=getFilePath(myfiledir).get(i).toString(); String filenames=getFileName(myfiledir).get(i).toString(); openDocument(filepaths); // 所有表格 Dispatch tables = Dispatch.get(doc, "Tables").toDispatch(); // 获取第1个表格 Dispatch table = Dispatch.call(tables, "Item", new Variant(1)).toDispatch(); // 获取表格值(固定10行) cus=new Cus(); cus.setId(filenames); cus.setProvince(getTxtFromCell(1, 1, 2)); cus.setProvince_manager(getTxtFromCell(1, 2, 2)); cus.setCustom(getTxtFromCell(1, 3, 2)); cus.setBusiness(getTxtFromCell(1, 4, 2)); cus.setReceiver(getTxtFromCell(1, 5, 2)); cus.setBill_info(getTxtFromCell(1, 6, 2)); cus.setInvoice_info(getTxtFromCell(1, 7, 2)); cus.setCus_info(getTxtFromCell(1, 8, 2)); cus.setGoods(getTxtFromCell(1, 9, 2)); cus.setRequirement(getTxtFromCell(1, 10, 2)); closeDocumentWithoutSave(); }else{ System.out.println("请关闭所有Word文档,并结束进程!"); break; } al1.add(cus); } close(); return al1; } //测试方法 // public static void main(String[] args)throws Exception{ // Jtest word = new Jtest(); // ArrayList<Cus> list=new ArrayList<Cus>(); // list=word.getFileContent(); // Iterator<Cus> it=list.iterator(); // while (it.hasNext()) { // System.out.println(it.next()); // // } // } }
2,插入数据DAO
package main.java.dao; import java.util.ArrayList; import java.util.Iterator; import main.java.Cus; import main.java.utils.Words; public class Dao { private Words words=null; private ArrayList<Cus> al=null; private Cus cus=null; //创建数据库 public void init() { DBAccess db = new DBAccess(); if(db.createConn()) { String sql = " create table CUSTOM ( " + " id varchar ( 30 ) primary key, " + " Province varchar ( 50 ), "+ " Province_manager varchar, ( 50 )" + " Custom varchar ( 50 ), "+ " Business varchar ( 50 ), "+ " Receiver varchar ( 50 ), "+ " Bill_info varchar ( 200), "+ " Invoice_info varchar ( 200 ), "+ " Cus_info varchar ( 50 ), "+ " Goods varchar ( 50 ), "+ " Requirement varchar ( 100 ))"; db.update(sql); db.closeStm(); db.closeConn(); } } //批量将WORD表格插入数据库 public void insertWordToDb() throws Exception{ DBAccess db = new DBAccess(); words=new Words(); al=new ArrayList<Cus>(); al=words.getFileContent(); Iterator<Cus> it=al.iterator(); while (it.hasNext()) { cus=new Cus(); cus=it.next(); if(db.createConn()) { String sql = "insert into custom values( ' " + cus.getId() + "','" + cus.getProvince() + "','" + cus.getProvince_manager() + "','" + cus.getCustom() + "','" + cus.getBusiness() + "','" + cus.getReceiver() + "','" + cus.getBill_info() + "','" + cus.getInvoice_info() + "','" + cus.getCus_info() + "','" + cus.getGoods() + "','" + cus.getRequirement() + "')"; db.update(sql); db.closeStm(); db.closeConn(); } } } }
3,增删改查封装
package main.java.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBAccess { private String drv = "org.h2.Driver"; private String url = "jdbc:h2:file:~/cus;AUTO_SERVER=TRUE"; private String usr = "sa"; private String pwd = ""; private Connection conn = null; private Statement stm = null; private ResultSet rs = null; public boolean createConn() { boolean b = false; try { Class.forName(drv).newInstance(); conn = DriverManager.getConnection(url, usr, pwd); b = true; } catch (SQLException e) { } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } return b; } public boolean update(String sql) { boolean b = false; try { stm = conn.createStatement(); stm.execute(sql); b = true; } catch (Exception e) { System.out.println(e.toString()); } return b; } public void query(String sql) { try { stm = conn.createStatement(); rs = stm.executeQuery(sql); } catch (Exception e) { } } public boolean next() { boolean b = false; try { if(rs.next())b = true; } catch (Exception e) { } return b; } public String getValue(String field) { String value = null; try { if(rs!=null)value = rs.getString(field); } catch (Exception e) { } return value; } public void closeConn() { try { if (conn != null) conn.close(); } catch (SQLException e) { } } public void closeStm() { try { if (stm != null) stm.close(); } catch (SQLException e) { } } public void closeRs() { try { if (rs != null) rs.close(); } catch (SQLException e) { } } public Connection getConn() { return conn; } public void setConn(Connection conn) { this.conn = conn; } public String getDrv() { return drv; } public void setDrv(String drv) { this.drv = drv; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public Statement getStm() { return stm; } public void setStm(Statement stm) { this.stm = stm; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsr() { return usr; } public void setUsr(String usr) { this.usr = usr; } }
4,POJO类
package main.java; public class Cus { private String Id; private String Province; private String Province_manager; private String Custom; private String Business; private String Receiver; private String Bill_info; private String Invoice_info; private String Cus_info; private String Goods; private String Requirement; public String getId() { return Id; } public void setId(String id) { Id = id; } public String getProvince() { return Province; } public void setProvince(String province) { Province = province; } public String getProvince_manager() { return Province_manager; } public void setProvince_manager(String provinceManager) { Province_manager = provinceManager; } public String getCustom() { return Custom; } public void setCustom(String custom) { Custom = custom; } public String getBusiness() { return Business; } public void setBusiness(String business) { Business = business; } public String getReceiver() { return Receiver; } public void setReceiver(String receiver) { Receiver = receiver; } public String getBill_info() { return Bill_info; } public void setBill_info(String billInfo) { Bill_info = billInfo; } public String getInvoice_info() { return Invoice_info; } public void setInvoice_info(String invoiceInfo) { Invoice_info = invoiceInfo; } public String getCus_info() { return Cus_info; } public void setCus_info(String cusInfo) { Cus_info = cusInfo; } public String getGoods() { return Goods; } public void setGoods(String goods) { Goods = goods; } public String getRequirement() { return Requirement; } public void setRequirement(String requirement) { Requirement = requirement; } }