java实现打印word功能_jacob打印word(.doc)或者excel(.xls) 【java实现】

该博客展示了如何利用Java结合Jacob库实现不打开文件直接打印Word(.docx)和Excel(.xlsx)文档的功能。通过创建ActiveXComponent实例,打开对应的应用程序,调用PrintOut方法完成打印操作,并确保在完成后正确释放资源。

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;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值