package cn.net.connor.std.processedit.word;

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

public class KExcelUtil {
	
	public static ActiveXComponent EXCELAPP = null;
	public static Dispatch WORKBOOKS = null;
	public static Dispatch SELECTION = null;
	public static Dispatch SHEETS;
	
	public static void startExcel(boolean initSTA) throws Exception{
		if(initSTA) {
			ComThread.InitSTA();
			LibraryLoader.loadJacobLibrary();
		}
		EXCELAPP = new ActiveXComponent("Excel.Application");
		EXCELAPP.setProperty("Visible", new Variant(false));
		// ax.setProperty("AutomationSecurity", new Variant(3));
		WORKBOOKS = EXCELAPP.getProperty("Workbooks").toDispatch();
	}
	
	public static void closeExcel(boolean realeaseComThread) {
		if(EXCELAPP!=null) {
			try {
				EXCELAPP.invoke("Quit", new Variant[] {});
				EXCELAPP = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(realeaseComThread) {
				try {
					ComThread.Release();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static Dispatch open(String path) {
		try {
			// return Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[] { path,
			// new Variant(false), new Variant(false) }, new int[1]).toDispatch();
			Dispatch doc = Dispatch.call(WORKBOOKS, "Open", path).toDispatch();
			SELECTION = Dispatch.get(EXCELAPP, "Selection").toDispatch();
			SHEETS = Dispatch.get(doc, "sheets").toDispatch();
			return doc;
		} catch (Exception e) {
		}
		return null;
	}
	
	public static void close(Dispatch document, boolean save) {
		// if (save) {
		// Dispatch.call(document, "Save");
		// }
		Dispatch.call(document, "Close", new Variant(save));
	}
	
    public static Dispatch getSheetByName(String name) {
        return Dispatch.invoke(SHEETS, "Item", Dispatch.Get, new Object[]{name}, new int[1]).toDispatch();
    }
    
    public static Dispatch getSheetByIndex(Integer index) {
        return Dispatch.invoke(SHEETS, "Item", Dispatch.Get, new Object[]{index}, new int[1]).toDispatch();
    }
    
    public static void copySheet(Dispatch sheet, String range) {
    	//Dispatch content = Dispatch.get(sheet, "Content").toDispatch();
    	Dispatch content = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] {range}, new int[1]).toDispatch();
    	Dispatch.call(content, "Copy");
    }
    
    
}