1. 程式人生 > >excel宏的Java調用

excel宏的Java調用

獲得 end quit dll return 工作薄 aac param isp

下載jacob-1.19.zip

https://sourceforge.net/projects/jacob-project/

jacob-1.19-x64.dll放到C:\Windows\System32目錄下

jacob.jar引入項目

技術分享圖片技術分享圖片?

excel需要保存為啟用宏的工作簿,後綴為.xlsm
文檔特定設置 宏
Sub 樣式設置()
‘ 樣式設置 宏
‘
    Range("A1:C1").Select
    Selection.Font.Bold = True
    With Selection.Font
        .Name = "微軟雅黑"
        .Size = 11
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0
        .ThemeFont = xlThemeFontNone
    End With
    With Selection.Font
        .Name = "微軟雅黑"
        .Size = 14
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0
        .ThemeFont = xlThemeFontNone
    End With
    ActiveWindow.SmallScroll Down:=-9
    Range("A1:C8").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    ActiveWindow.SmallScroll Down:=-6
    Range("A1:C1").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = -0.149998474074526
        .PatternTintAndShade = 0
    End With
    Range("G3").Select
End Sub
Sub 文檔特定設置()
‘ 文檔特定設置 宏
End Sub
技術分享圖片
樣式設置 宏
Sub 樣式設置()
‘ 樣式設置 宏
‘
    Range("A1:C1").Select
    Selection.Font.Bold = True
    With Selection.Font
        .Name = "微軟雅黑"
        .Size = 11
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0
        .ThemeFont = xlThemeFontNone
    End With
    With Selection.Font
        .Name = "微軟雅黑"
        .Size = 14
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0
        .ThemeFont = xlThemeFontNone
    End With
    ActiveWindow.SmallScroll Down:=-9
    Range("A1:C8").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    ActiveWindow.SmallScroll Down:=-6
    Range("A1:C1").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = -0.149998474074526
        .PatternTintAndShade = 0
    End With
    Range("G3").Select
End Sub
Sub 文檔特定設置()
‘ 文檔特定設置 宏
End Sub
技術分享圖片
JacobExcelTool.java
/*
 * Copyright © 2019 [email protected] Inc. All rights reserved
 * @package: com.ibm.jacob
 * @version V1.0
 */
package com.ibm.jacob;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
 * @author Moses *
 * @Date 2019/4/1
 */
public class JacobExcelTool {
    /**
     * Excel對象
     */
    private ActiveXComponent xl = null;
    /**
     * 工作簿對象
     */
    private Dispatch workbooks = null;
    /**
     * 具體工作簿
     */
    private Dispatch workbook = null;
    /**
     * 獲得sheets集合對象
     */
    private Dispatch sheets = null;
    /**
     * 當前sheet
     */
    private Dispatch currentSheet = null;

    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.InitMTA(true);可同時運行多個
            ComThread.InitSTA();
            // Excel對象
            if (xl == null) {
                xl = new ActiveXComponent("Excel.Application");
            }
            // 設置是否顯示打開excel
            xl.setProperty("Visible", new Variant(visible));
            // 工作簿對象
            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 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));
    }

    /**
     * 調用excel宏
     *
     * @param macroName 宏名
     * @param param     傳遞參數
     */
    public void callMacro(String macroName, Object param) {
        Dispatch.call(xl, "Run", new Variant(macroName), new Variant(param));
    }

    /**
     * 單元格寫入值
     *
     * @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();
        return Dispatch.get(cell, "Value");
    }

    /**
     * 清空原始變量
     */
    private void initComponents() {
        workbook = null;
        currentSheet = null;
        sheets = null;
    }
}
技術分享圖片
TestJacob.java
/*
 * Copyright © 2019 [email protected] Inc. All rights reserved
 * @package: com.ibm.jacob
 * @version V1.0
 */
package com.ibm.jacob;

import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.junit.Test;

/**
 * @author Moses *
 * @Date 2019/4/1
 */
public class TestJacob {
    @Test
    public void testMacro() {
        JacobExcelTool tool = new JacobExcelTool();
        //打開
        tool.OpenExcel("D:/temp/宏測試.xlsm", false, false);
        Dispatch sheet = tool.getSheetByName("Sheet1");
        for (int i = 2; i <= 7; i++) {
            tool.setValue(sheet, "B" + i, "value", i * 1.2);
        }
        //調用Excel宏
        tool.callMacro("文檔特定設置");
        //調用Excel宏
        tool.callMacro("樣式設置");
        Variant num = tool.getValue("B8", sheet);
        System.out.println(num);
        //關閉並保存,釋放對象
        tool.CloseExcel(true, true);
    }
}
技術分享圖片

技術分享圖片技術分享圖片?

excel宏的Java調用