1. 程式人生 > >通過java代碼實現調用excel當中的宏的操作。

通過java代碼實現調用excel當中的宏的操作。

合同 println ren () 版本 imp port exc length

最近做的項目是自動化生成基金的交易合同的操作。然後就想著通過java代碼去操作Excel當中的宏按鈕,然後生成word版本的合同的操作。

具體的java代碼如下:

import org.junit.Assert;
import org.junit.Test;

public class ExcelToolsServiceTest {

    private ExcelToolsService service;

    @Test
    public void testMacro() {
        try {
            String path = "C:/Users/admin.admin-PC.000/Desktop/vb/合並的模板/合同模板.xlsm
"; service = new ExcelToolsService(); service.execMacro(path, "文本替換.生成文檔"); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } }


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


public class ExcelToolsService {


public void execMacro(String excelPath, String macroName, Variant... params) throws Exception {


ActiveXComponent excel = null;
Dispatch workbooks = null;
Dispatch workbook = null;
long start = System.currentTimeMillis();
System.out.println(start);

try {
ComThread.InitSTA();


excel = new ActiveXComponent("Excel.Application");
workbooks = excel.getProperty("Workbooks").toDispatch();
workbook = Dispatch.call(workbooks, "Open", excelPath).toDispatch();
if (null == params || params.length < 1) {
Dispatch.call(excel, "Run", new Variant(macroName));
} else {
Dispatch.call(excel, "Run", new Variant(macroName), params);
}
Dispatch.call(workbook, "Save");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != workbook) {// 關閉文檔
Dispatch.call(workbook, "Close", new Variant(false));
}
if (null != workbooks) {
Dispatch.call(workbooks, "Close");
}
if (null != excel) {
excel.invoke("Quit", new Variant[] {});
}


// 關閉Excel進程
ComThread.Release();


long end = System.currentTimeMillis();
System.out.println("處理文件[{}]宏[{}],共耗時{}s" + excelPath + macroName
+ ((end - start) / 1000 + 1));
}
}


}

 

至此實現了通過Excel的宏自動化的生成基金的合同的操作。

通過java代碼實現調用excel當中的宏的操作。