Jacob項目:https://sourceforge.net/projects/jacob-project/
轉自:https://blog.csdn.net/ZY_extreme/article/details/80019009
轉自:http://www.360doc.com/content/14/0310/11/12385684_359224303.shtml
轉自:https://blog.csdn.net/ZY_extreme/article/details/80007232
轉自:https://www.cnblogs.com/vczh/p/5692527.html
轉自:https://blog.csdn.net/javadakangxiaobai/article/details/83422396
轉自:https://blog.csdn.net/a0701302/article/details/62236470

/** 2018年4月20日 **/ import com.jacob.com.*; import com.jacob.activeX.*; public class ReadExcel { private static ActiveXComponent xl; private static Dispatch workbooks = null; private static Dispatch workbook = null; private static Dispatch sheet = null; private static String filename = null; private static boolean readonly = false; public static void main(String[] args) { String file = "E:\\frequently\\study\\ex.xlsx"; OpenExcel(file, false);// false為不顯示打開Excel SetValue("1","A1","Value","2"); System.out.println(GetValue("基礎設施情況","G10")); CloseExcel(false); } // 打開Excel文檔 private static void OpenExcel(String file, boolean f) { try { filename = file; xl = new ActiveXComponent("Excel.Application"); xl.setProperty("Visible", new Variant(f)); workbooks = xl.getProperty("Workbooks").toDispatch(); workbook = Dispatch.invoke(workbooks, "Open", Dispatch.Method, new Object[] { filename, new Variant(false), new Variant(readonly) }, // 是否以只讀方式打開 new int[1]).toDispatch(); } catch (Exception e) { e.printStackTrace(); } } // 關閉Excel文檔 private static void CloseExcel(boolean f) { try { Dispatch.call(workbook, "Save"); Dispatch.call(workbook, "Close", new Variant(f)); } catch (Exception e) { e.printStackTrace(); } finally { xl.invoke("Quit", new Variant[] {}); } } // 寫入值--以編號讀寫sheet private static void SetValue(String sheetItem ,String position, String type, String value) { // sheet = Dispatch.get(workbook,"ActiveSheet").toDispatch(); Dispatch sheets = Dispatch.get(workbook, "Sheets").toDispatch(); // 以編號讀寫sheet sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get, new Object[] { new String(sheetItem) }, new int[1]) .toDispatch(); Dispatch cell = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] { position }, new int[1]) .toDispatch(); Dispatch.put(cell, type, value); } // 讀取值--以名稱讀寫sheet private static String GetValue(String sheetItem,String position) { // sheet = Dispatch.get(workbook,"ActiveSheet").toDispatch(); Dispatch sheets = Dispatch.get(workbook, "Sheets").toDispatch(); // 以名稱讀寫sheet sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get, new Object[] { new String(sheetItem) }, new int[1]) .toDispatch(); Dispatch cell = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] { position }, new int[1]) .toDispatch(); String value = Dispatch.get(cell, "Value").toString(); return value; } }

import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class JacobExcelTool { private static ActiveXComponent xl = null; //Excel對象(防止打開多個) private static Dispatch workbooks = null; //工作簿對象 private Dispatch workbook = null; //具體工作簿 private Dispatch sheets = null;// 獲得sheets集合對象 private Dispatch currentSheet = null;// 當前sheet public ActiveXComponent getXl() { return xl; } public Dispatch getWorkbooks() { return workbooks; } public Dispatch getWorkbook() { return workbook; } /** * 打開excel文件 * @param filepath 文件路徑名稱 * @param visible 是否顯示打開 * @param readonly 是否只讀方式打開 */ public void OpenExcel(String filepath, boolean visible, boolean readonly) { try { initComponents(); //清空原始變量 ComThread.InitSTA(); if(xl==null) xl = new ActiveXComponent("Excel.Application"); //Excel對象 xl.setProperty("Visible", new Variant(visible));//設置是否顯示打開excel if(workbooks==null) workbooks = xl.getProperty("Workbooks").toDispatch(); //工作簿對象 workbook = Dispatch.invoke( //打開具體工作簿 workbooks, "Open", Dispatch.Method, new Object[] { filepath, new Variant(false), new Variant(readonly) },// 是否以只讀方式打開 new int[1]).toDispatch(); } catch (Exception e) { e.printStackTrace(); releaseSource(); } } /** * 工作簿另存為 * @param filePath 另存為的路徑 */ public void SaveAs(String filePath){ Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[] { filePath, new Variant(44) }, new int[1]); } /** * 關閉excel文檔 * @param f 含義不明 (關閉是否保存?默認false) */ public void CloseExcel(boolean f,boolean quitXl) { try { Dispatch.call(workbook, "Save"); Dispatch.call(workbook, "Close", new Variant(f)); } catch (Exception e) { e.printStackTrace(); } finally { if(quitXl){ releaseSource(); } } } /** * 釋放資源 */ public static void releaseSource(){ if(xl!=null){ xl.invoke("Quit", new Variant[] {}); xl = null; } workbooks = null; ComThread.Release(); System.gc(); } /** * 添加新的工作表(sheet),(添加后為默認為當前激活的工作表) */ public Dispatch addSheet() { return Dispatch.get(Dispatch.get(workbook, "sheets").toDispatch(), "add").toDispatch(); } /** * 修改當前工作表的名字 * @param newName */ public void modifyCurrentSheetName(String newName) { Dispatch.put(getCurrentSheet(), "name", newName); } /** * 得到當前工作表的名字 * @return */ public String getCurrentSheetName() { return Dispatch.get(getCurrentSheet(), "name").toString(); } /** * 得到工作薄的名字 * @return */ public String getWorkbookName() { if(workbook==null) return null; return Dispatch.get(workbook, "name").toString(); } /** * 得到sheets的集合對象 * @return */ public Dispatch getSheets() { if(sheets==null) sheets = Dispatch.get(workbook, "sheets").toDispatch(); return sheets; } /** * 得到當前sheet * @return */ public Dispatch getCurrentSheet() { currentSheet = Dispatch.get(workbook, "ActiveSheet").toDispatch(); return currentSheet; } /** * 通過工作表名字得到工作表 * @param name sheetName * @return */ public Dispatch getSheetByName(String name) { return Dispatch.invoke(getSheets(), "Item", Dispatch.Get, new Object[]{name}, new int[1]).toDispatch(); } /** * 通過工作表索引得到工作表(第一個工作簿index為1) * @param index * @return sheet對象 */ public Dispatch getSheetByIndex(Integer index) { return Dispatch.invoke(getSheets(), "Item", Dispatch.Get, new Object[]{index}, new int[1]).toDispatch(); } /** * 得到sheet的總數 * @return */ public int getSheetCount() { int count = Dispatch.get(getSheets(), "count").toInt(); return count; } /** * 調用excel宏 * @param macroName 宏名 */ public void callMacro(String macroName){ Dispatch.call(xl, "Run",new Variant(macroName)); } /** * 單元格寫入值 * @param sheet 被操作的sheet * @param position 單元格位置,如:C1 * @param type 值的屬性 如:value * @param value */ public void setValue(Dispatch sheet, String position, String type, Object value) { Dispatch cell = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] { position }, new int[1]) .toDispatch(); Dispatch.put(cell, type, value); } /** * 單元格讀取值 * @param position 單元格位置,如: C1 * @param sheet * @return */ public Variant getValue(String position, Dispatch sheet) { Dispatch cell = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] { position }, new int[1]).toDispatch(); Variant value = Dispatch.get(cell, "Value"); return value; } private void initComponents(){ workbook = null; currentSheet = null; sheets = null; } }

package java_word; /** 1580536707@qq.com 2018年4月19日 **/ import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class DispatchTest { public static String fileRealPath = "C:\\Users\\Desktop\\原文檔.doc"; public static String saveNewRealpath = "C:\\Users\\Desktop\\副本.doc"; public static void main(String[] args) { //這是copy全文方法 ComThread.InitSTA(); //被復制的文檔 ActiveXComponent word2= new ActiveXComponent("Word.Application"); word2.setProperty("Visible", new Variant(false)); Dispatch documents2 = word2.getProperty("Documents").toDispatch(); //復制的文檔 ActiveXComponent word= new ActiveXComponent("Word.Application"); word.setProperty("Visible", new Variant(false)); Dispatch documents = word.getProperty("Documents").toDispatch(); Dispatch doc2 = Dispatch.call(documents2, "Open",saveNewRealpath ).toDispatch(); //復制模板的內容 Dispatch doc = Dispatch.call(documents, "Open",fileRealPath).toDispatch(); Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); /*Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch(); Dispatch paragraph = Dispatch.call(paragraphs, "Item",new Variant(40)).toDispatch(); Dispatch range = Dispatch.get(paragraph, "Range").toDispatch(); Dispatch.call(range, "Copy");*/ Dispatch.call(wordContent, "Copy"); Dispatch selection = Dispatch.get(word2, "Selection").toDispatch(); Dispatch textRange = Dispatch.get(selection, "Range").toDispatch(); Dispatch.call(textRange, "Paste"); Dispatch.call(doc2, "Save"); Dispatch.call(doc2, "Close", new Variant(true)); Dispatch.call(word2, "Quit"); doc2 = null; word2 = null; Dispatch.call(doc, "Close", new Variant(true)); Dispatch.call(word , "Quit"); doc = null; word = null; documents2 = null; ComThread.Release(); } } --------------------- 作者:花好人間 來源:CSDN 原文:https://blog.csdn.net/ZY_extreme/article/details/80007232 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

package com.HeiBeiEDU.test2; import java.io.File; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class PrintDemo { public static boolean printOfficeFile(File f) { if (f != null && f.exists()) { String fileNameString = f.getName(); String postfixString = Utils.getPostfix(fileNameString); if (postfixString.equalsIgnoreCase("xls") || postfixString.equalsIgnoreCase("xlsx")) { /** * 功能:實現excel打印工作 */ ComThread.InitSTA(); ActiveXComponent xl = new ActiveXComponent("Excel.Application"); try { // System.out.println("version=" + // xl.getProperty("Version")); // 不打開文檔 Dispatch.put(xl, "Visible", new Variant(false)); Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); // 打開文檔 Dispatch excel = Dispatch.call(workbooks, "Open", f.getAbsolutePath()).toDispatch(); // 橫向打印(2013/05/24) // Dispatch currentSheet = Dispatch.get(excel, // "ActiveSheet") // .toDispatch(); // Dispatch pageSetup = Dispatch // .get(currentSheet, "PageSetup").toDispatch(); // Dispatch.put(pageSetup, "Orientation", new Variant(2)); // 每張表都橫向打印2013-10-31 Dispatch sheets = Dispatch.get((Dispatch) excel, "Sheets").toDispatch(); // 獲得幾個sheet int count = Dispatch.get(sheets, "Count").getInt(); // System.out.println(count); for (int j = 1; j <= count; j++) { Dispatch sheet = Dispatch .invoke(sheets, "Item", Dispatch.Get, new Object[] { new Integer(j) }, new int[1]) .toDispatch(); Dispatch pageSetup = Dispatch.get(sheet, "PageSetup").toDispatch(); Dispatch.put(pageSetup, "Orientation", new Variant(2)); Dispatch.call(sheet, "PrintOut"); } // 開始打印 if (excel != null) { // Dispatch.call(excel, "PrintOut"); // 增加以下三行代碼解決文件無法刪除bug Dispatch.call(excel, "save"); Dispatch.call(excel, "Close", new Variant(true)); excel = null; } xl.invoke("Quit", new Variant[] {}); xl = null; return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { // 始終釋放資源 ComThread.Release(); } } else if (postfixString.equalsIgnoreCase("doc") || postfixString.equalsIgnoreCase("docx")) { ComThread.InitSTA(); ActiveXComponent wd = new ActiveXComponent("Word.Application"); try { // 不打開文檔 Dispatch.put(wd, "Visible", new Variant(false)); Dispatch document = wd.getProperty("Documents").toDispatch(); // 打開文檔 Dispatch doc = Dispatch .invoke(document, "Open", Dispatch.Method, new Object[] { f.getAbsolutePath() }, new int[1]) .toDispatch(); // 開始打印 if (doc != null) { Dispatch.call(doc, "PrintOut"); // 增加以下三行代碼解決文件無法刪除bug Dispatch.call(doc, "save"); Dispatch.call(doc, "Close", new Variant(true)); doc = null; } wd.invoke("Quit", new Variant[] {}); wd = null; return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { // 始終釋放資源 ComThread.Release(); } } else { return false; } } else { return false; } } public static void main(String[] args) { PrintDemo.printOfficeFile(new File("hehe.xls")); } }

/** * 生成excel * * @throws UnsupportedEncodingException */ private void moveToControlExcel(OutputStream os, List<SupervisionProblem> entityList) throws UnsupportedEncodingException { String HSSFname = "自動監控設施現場檢查存在問題詳表"; HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(HSSFname); sheet.getPrintSetup().setLandscape(true); // 創建標題樣式 HSSFCellStyle style = wb.createCellStyle(); style.setWrapText(true); // 設置允許換行 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平 style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下邊框 style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左邊框 style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上邊框 style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右邊框 // 設置字體 HSSFFont font = wb.createFont(); font.setFontName("華文楷體"); font.setFontHeightInPoints((short) 16);// 設置字體大小 style.setFont(font);// 樣式,居中 // 創建正文數據樣式 HSSFCellStyle style2 = wb.createCellStyle(); style2.setWrapText(true); // 設置允許換行 style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直 style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平 style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下邊框 style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左邊框 style2.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上邊框 style2.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右邊框 HSSFFont font2 = wb.createFont(); font2.setFontName("宋體"); font2.setFontHeightInPoints((short) 8); style2.setFont(font2);// 選擇需要用到的字體格式 String fileName = new String(HSSFname.getBytes(), System.getProperty("file.encoding")); fileName = java.net.URLEncoder.encode(fileName, "UTF-8"); // 創建第一行 標題 // 設置第一行第一到第7個單元格合並 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6)); HSSFRow rowTitle = sheet.createRow(0); for (int i = 0; i < 7; i++) { HSSFCell cellone = rowTitle.createCell(i); // 第一行第一列 cellone.setCellValue(HSSFname);// 表格的第一行第一列顯示的數據 cellone.setCellStyle(style);// 樣式,居中 } rowTitle.setHeight((short) 1100); // 第二行 HSSFRow row2 = sheet.createRow(1); row2.setHeight((short) 480); String colums[] = new String[] { "序號", "企業名稱", "問題發現時間", "問題開始時間", "整改期限", "問題類別", "現場檢查發現的問題" }; // 插入列名 for (int i = 0; i < colums.length; i++) { HSSFCell row21 = row2.createCell(i); row21.setCellValue(new HSSFRichTextString(colums[i]));// 表格的第一行第一列顯示的數據 // 數據字體 row21.setCellStyle(style2); if (i == 0) { sheet.setColumnWidth(i, 2000);// 設置單元格寬度 } else if (i == 1) { sheet.setColumnWidth(i, 6500);// 設置單元格寬度 } else if (i == 2) { sheet.setColumnWidth(i, 3000);// 設置單元格寬度 } else if (i == 3) { sheet.setColumnWidth(i, 3000);// 設置單元格寬度 } else if (i == 4) { sheet.setColumnWidth(i, 3000);// 設置單元格寬度 } else if (i == 5) { sheet.setColumnWidth(i, 4500);// 設置單元格寬度 } else if (i == 6) { sheet.setColumnWidth(i, 7300);// 設置單元格寬度 } } // 插入數據 for (int j = 0; j < entityList.size(); j++) { SupervisionProblem sp = entityList.get(j); HSSFRow rowData = sheet.createRow((2 + j)); rowData.setHeight((short) 480); for (int i = 0; i < colums.length; i++) { HSSFCell cData = rowData.createCell(i); cData.setCellStyle(style2); if (i == 0) { cData.setCellValue(j + 1); // 序號 } else if (i == 1) { cData.setCellValue(sp.getEnterpriseName()); } else if (i == 2) { cData.setCellValue(sp.getCreateTime()); } else if (i == 3) { cData.setCellValue(sp.getProblemStartTime()); } else if (i == 4) { cData.setCellValue(sp.getRecEndTime()); } else if (i == 5) { cData.setCellValue(sp.getProblemTypeName()); } else if (i == 6) { cData.setCellValue(sp.getProblemDescription()); } } } try { wb.write(os); os.close(); os.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (os != null) { try { os.close(); os.flush(); } catch (IOException e) { e.printStackTrace(); } } if (wb != null) { try { wb.close(); } catch (IOException e) { e.printStackTrace(); } } } } --------------------- 作者:追夢的王小白 來源:CSDN 原文:https://blog.csdn.net/javadakangxiaobai/article/details/83422396 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

/** * 打印Excel文件 * @param filePath 文件路徑 */ public static boolean printFileAction(String filePath){ boolean returnFlg = false; try { ComThread.InitSTA(); ActiveXComponent xl = new ActiveXComponent("Excel.Application"); // 不打開文檔 Dispatch.put(xl, "Visible", new Variant(true)); Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); // win下路徑處理(把根目錄前的斜杠刪掉) filePath = filePath.replace("/E:/","E:/"); // 判斷文件是否存在 boolean fileExistFlg = fileExist(filePath); if (fileExistFlg) { Dispatch excel=Dispatch.call(workbooks,"Open",filePath).toDispatch(); // 開始打印 Dispatch.get(excel,"PrintOut"); returnFlg = true; } } catch (Exception e) { e.printStackTrace(); } finally { // 始終釋放資源 ComThread.Release(); } return returnFlg; } --------------------- 作者:star0701 來源:CSDN 原文:https://blog.csdn.net/a0701302/article/details/62236470 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

/** * 打印Excel文件 * @param filePath 文件路徑 */ public static boolean printFileAction(String filePath,String printerName){ boolean returnFlg = false; try { ComThread.InitSTA(); ActiveXComponent xl = new ActiveXComponent("Excel.Application"); // 不打開文檔 Dispatch.put(xl, "Visible", new Variant(true)); Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); // win下路徑處理(把根目錄前的斜杠刪掉) filePath = filePath.replace("/E:/","E:/"); Object[] object = new Object[8]; object[0] = Variant.VT_MISSING; object[1] = Variant.VT_MISSING; object[2] = Variant.VT_MISSING; object[3] = new Boolean(false); object[4] = printerName; object[5] = new Boolean(false); object[6] = Variant.VT_MISSING; object[7] = Variant.VT_MISSING; // 判斷文件是否存在 boolean fileExistFlg = fileExist(filePath); if (fileExistFlg) { Dispatch excel=Dispatch.call(workbooks,"Open",filePath).toDispatch(); // 開始打印 Dispatch.callN(excel,"PrintOut",object); returnFlg = true; } } catch (Exception e) { e.printStackTrace(); } finally { // 始終釋放資源 ComThread.Release(); } return returnFlg; } --------------------- 作者:star0701 來源:CSDN 原文:https://blog.csdn.net/a0701302/article/details/62236470 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

/** * 判斷文件是否存在. * @param filePath 文件路徑 * @return */ private static boolean fileExist(String filePath){ boolean flag = false; try { File file = new File(filePath); flag = file.exists(); }catch (Exception e) { e.printStackTrace(); } return flag; } --------------------- 作者:star0701 來源:CSDN 原文:https://blog.csdn.net/a0701302/article/details/62236470 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!