标签:end code app component [] cron xls variant public
最近做的项目是自动化生成基金的交易合同的操作。然后就想着通过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的宏自动化的生成基金的合同的操作。
标签:end code app component [] cron xls variant public
原文地址:https://www.cnblogs.com/gxgd/p/9306314.html