package com.xfzx.test.POI.main;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class JacobPress {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
printWord("D:/txt.docx");
//printExcel("D:/提醒通知明细通用模板.xlsx");
}
public static void printExcel(String filePath) {
/**
* 功能:实现打印工作
*/
ComThread.InitSTA();
ActiveXComponent xl = new ActiveXComponent("Excel.Application");
try {
// System.out.println("version=" + xl.getProperty("Version"));
// 不打开文档
Dispatch.put(xl, "Visible", new Variant(true));
Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
// 打开文档
Dispatch excel = Dispatch.call(workbooks, "Open", filePath)
.toDispatch();
// 开始打印
Dispatch.call(excel, "PrintOut");
xl.invoke("Quit", new Variant[] {});
} catch (Exception e) {
e.printStackTrace();
} finally {
// 始终释放资源
ComThread.Release();
}
}
public static void printWord(String filePath) {
ComThread.InitSTA();
ActiveXComponent wd = new ActiveXComponent("Word.Application");
try {
// 不打开文档
Dispatch.put(wd, "Visible", new Variant(true));
Dispatch document = wd.getProperty("Documents").toDispatch();
// 打开文档
Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method,
new Object[] { filePath }, new int[1]).toDispatch();
// 开始打印
Dispatch.callN(doc, "PrintOut");
wd.invoke("Quit", new Variant[] {});
} catch (Exception e) {
e.printStackTrace();
} finally {
// 始终释放资源
ComThread.Release();
}
}
// 获得文件后缀名
public static String getPostfix(String inputFilePath) {
String[] p = inputFilePath.split("\\.");
if (p.length > 0) {// 判断文件有无扩展名
// 比较文件扩展名
return p[p.length - 1];
} else {
return null;
}
}
}
该博客展示了如何利用Java结合Jacob库实现不打开文件直接打印Word(.docx)和Excel(.xlsx)文档的功能。通过创建ActiveXComponent实例,打开对应的应用程序,调用PrintOut方法完成打印操作,并确保在完成后正确释放资源。
或者excel(.xls) 【java实现】&spm=1001.2101.3001.5002&articleId=114559035&d=1&t=3&u=2410bcf26958458284722dde724eeb4f)
4254

被折叠的 条评论
为什么被折叠?



