使用jacob写MS Project
前些日子简单的使用 jacob 实现写数据到 MS Project,怕过些日子忘掉,所以整理了下,没有深入,只是简单的实现了下
Jacob 是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁
使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用
使用 jacob 实现写数据到 MS Project
控制器
@PostMapping("/createMpp") public String createMpp(@RequestBody JSONObject jsonParam) { String fileName = (String)jsonParam.get("fileName"); if(fileName==null||fileName.equals("")) { return "fileName is not null"; } try { Tasks dd = new Tasks(); Boolean rs = dd.create(fileName); if(rs){ return "ok"; } } catch (Exception e) { e.printStackTrace(); } return "error"; }
Tasks.java
package com.ppt.jacob.common; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class Tasks { private static void setTaskValue(Dispatch task, TaskBean taskBean, int level) { Dispatch.put(task, "Name", taskBean.getName()); Dispatch.put(task, "Duration", 1); Dispatch.put(task, "Start", "2018年1月1日"); Dispatch.put(task, "Finish", "2018年3月1日"); Dispatch.put(task, "PercentWorkComplete", "11"); Dispatch.put(task, "OutlineLevel", level); } public boolean create(String fileName) { ActiveXComponent app = null; try { app = new ActiveXComponent("MSProject.Application"); app.setProperty("Visible", new Variant(false)); Dispatch projects = app.getProperty("Projects").toDispatch(); //添加一个项目 Dispatch project = Dispatch.call(projects, "Add").toDispatch(); //生成一个task集合 Dispatch tasks = Dispatch.get(project, "Tasks").toDispatch(); for (int i = 0; i < 10; i++) { Dispatch task = Dispatch.call(tasks, "Add").toDispatch(); TaskBean taskBean = TaskBean.builder().name("name" + i).build(); setTaskValue(task, taskBean, 1); } StringBuilder name = new StringBuilder("E:/test/"); name.append(fileName).append(".mpp"); Dispatch.invoke(project, "SaveAs", Dispatch.Method, new Object[]{name.toString(), new Variant(0)}, new int[1]); } catch (Exception e) { e.printStackTrace(); } finally { if (app != null) app.invoke("Quit", new Variant[]{}); } return true; } }
参考文档https://docs.microsoft.com/zh-cn/office/vba/api/project.application