package com.sunxung.factoring.component.util;

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

/**
 * @author yanglin
 * @description 工具类：解决Execle弹出版本不适合问题
 * @date 2019/4/30
 */
public class JacobExcelTool {

    private ActiveXComponent xl = null; // Excel对象
    private Dispatch workbooks = null; // 工作簿对象
    private Dispatch workbook = null; // 具体工作簿

    public ActiveXComponent getXl() {
        return xl;
    }

    public Dispatch getWorkbooks() {
        return workbooks;
    }

    public Dispatch getWorkbook() {
        return workbook;
    }

    /**
     * 打开excel文件
     *
     * @param filepath 文件路径名称
     * @param visible 是否显示打开
     */
    public void OpenExcel(String filepath, boolean visible) {
        try {
            initComponents(); // 清空原始变量
            ComThread.InitSTA();// 仅允许同时运行一个线程，其他线程锁住
            // ComThread.InitMTA(true);//可同时运行多个
            if (xl == null)
                xl = new ActiveXComponent("Excel.Application"); // Excel对象
            xl.setProperty("Visible", new Variant(visible));// 设置是否显示打开excel
            if (workbooks == null)
                workbooks = xl.getProperty("Workbooks").toDispatch(); // 工作簿对象
            workbook = Dispatch.invoke( // 打开具体工作簿
                    workbooks, "OpenXML", Dispatch.Method, new Object[] {
                            filepath
                    }, new int[1]).toDispatch();
            /*
             * workbook = Dispatch.invoke( // 打开具体工作簿 workbooks, "Open", Dispatch.Method, new Object[] { filepath, new
             * Variant(false), new Variant(readonly) }, // 是否以只读方式打开 new int[1]).toDispatch();
             */
        } catch (Exception e) {
            e.printStackTrace();
            releaseSource();
        }
    }

    /**
     * 工作簿另存为
     *
     * @param filePath 另存为的路径
     */
    public void SaveAs(String filePath) {
        Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[] {
                filePath, new Variant(51)
        }, new int[1]);
    }

    /**
     * 关闭excel文档
     *
     * @param f 含义不明 （关闭是否保存？默认false）
     */
    public void CloseExcel(boolean f, boolean quitXl) {
        try {
            // Dispatch.call(workbook, "Save");
            Dispatch.call(workbook, "Close", new Variant(f));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (quitXl) {
                releaseSource();
            }
        }
    }

    /**
     * 释放资源
     */
    public void releaseSource() {
        if (xl != null) {
            xl.invoke("Quit", new Variant[] {});
            xl = null;
        }
        workbooks = null;
        ComThread.Release();
        System.gc();
    }

    private void initComponents() {
        workbook = null;
    }
}
