jacob xls与xlsx格式互转

一、jacob使用前准备

1、jacob官网下载jacob(下载之后具体的使用请自行百度,网上很多关于jacob使用的文章)
2、安装office(jacob实现格式转换的本质是调用office另存为,本文是基于office 2010)

二、excel格式互转

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

import java.io.File;

public class test{


    /***jacob操作office内部对应代码 */
    /*** xlsx 格式 */
    private static final int XLSX_FMT = 51;
    /*** xls 格式 */
    private static final int XLS_FMT = 1;
    /**
     * 根据格式类型转换 Excel 文件
     *
     * @param srcPath  源文件
     * @param descPath 目标文件
     * @param fmt      所转格式
     */
    private static File converteExcelfmt(String srcPath, String descPath, int fmt) throws Exception {
        // 实例化ComThread线程与ActiveXComponent
        ComThread.InitSTA();
        ActiveXComponent wordApp = new ActiveXComponent("Excel.Application");
        try {
            // 文件隐藏时进行应用操作
            wordApp.setProperty("Visible", new Variant(false));
            // 实例化模板Workbooks对象
            Dispatch workbooks = wordApp.getProperty("Workbooks").toDispatch();
            // 打开Workbooks进行另存为操作
            Dispatch doc = Dispatch.invoke(workbooks, "Open", Dispatch.Method, new Object[]{srcPath, new Variant(true), new Variant(true)}, new int[1]).toDispatch();
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{descPath, new Variant(fmt)}, new int[1]);
            Dispatch.call(doc, "Close", new Variant(false));
            return new File(descPath);
        } catch (Exception e) {
            throw e;
        } finally {
            // 释放线程与ActiveXComponent
            wordApp.invoke("Quit", new Variant[]{});
            ComThread.Release();
        }
    }
    public static void main(String[] args) throws Exception {
         String str1="C:\\test.xls";
         String str2="C:\\testxxx.xlsx";
         String str3="C:\\testx.xls";
         //xls文件转xlsx文件
         converteExcelfmt(str1,str2,XLSX_FMT);
        //xlsx文件转xls文件
        converteExcelfmt(str2,str3,XLS_FMT);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值