jeans 发表于 2013-1-27 04:46:10

给Excel加保护密码

//给Excel加保护密码public class ExcelTest {private static ActiveXComponent xl;private static Dispatch workbooks = null;private static Dispatch workbook = null;private static Dispatch sheet = null;private static String filename =null;private static boolean readonly = false;    public static void main(String[] args) {   String file = "C:\\tmp\\jeans.xls";   OpenExcel(file,false);   SetValue("A1","Value","2");   System.out.println(GetValue("A3"));   CloseExcel(false);}    private static void OpenExcel(String file,boolean f) {    try {      filename = file;      xl = new ActiveXComponent("Excel.Application");      xl.setProperty("Visible", new Variant(f));      workbooks = xl.getProperty("Workbooks").toDispatch();      workbook = Dispatch.invoke(workbooks,                "Open",               Dispatch.Method, new Object[]{filename,new Variant(false), new Variant(readonly)},new int ).toDispatch();         Dispatch xlo = xl.getObject();         Dispatch ap = Dispatch.get(xlo, "Application").toDispatch();         Dispatch as = Dispatch.get(ap, "ActiveSheet").toDispatch();         Variant asp = Dispatch.call(as, "Protect","password",new Variant(true),new Variant(true),new Variant(true));             }catch(Exception e) {e.printStackTrace();}}    private static void CloseExcel(boolean f) {   try {    Dispatch.call(workbook,"Save");         Dispatch.call(workbook, "Close", new Variant(f));      } catch (Exception e) {         e.printStackTrace();   } finally { xl.invoke("Quit", new Variant[] {});   }}    private static void SetValue(String position,String type,String value){   sheet = Dispatch.get(workbook,"ActiveSheet").toDispatch();      Dispatch cell = Dispatch.invoke(sheet, "Range", Dispatch.Get,new Object[] {position},new int).toDispatch();      Dispatch.put(cell, type, value);}private static String GetValue(String position) { Dispatch cell = Dispatch.invoke(sheet,"Range",Dispatch.Get,new Object[] {position},new int).toDispatch(); String value = Dispatch.get(cell,"Value").toString();   return value;}} 
页: [1]
查看完整版本: 给Excel加保护密码