0

我正在尝试另存为 excel 文件,但它给出了一个错误:无法将名称映射到 dispid:FileSaveAs。

private ActiveXComponent objExcel = new ActiveXComponent("Excel.Application");
excelObject = objExcel.getObject();
Dispatch.put(excelObject, "Visible", new Variant(false));
workbook = objExcel.getProperty("Workbooks").toDispatch();
workbook = Dispatch.call(workbook, "Open", filename).toDispatch();
Dispatch oExcel = Dispatch.call(objExcel, "Workbooks").getDispatch();
Dispatch.call(workbook, "FileSaveAs", filename, new Variant(51));

变体的参数取自: http: //msdn.microsoft.com/en-us/library/bb241279 (v=office.12).aspx

谁能告诉我代码中的问题在哪里?谢谢

4

3 回答 3

1

我不确定我是否使用正确的方法来做到这一点,但它确实有效

public Boolean savesAS(String path, String nameFile){

    ComThread.InitSTA();

    ActiveXComponent excel = new ActiveXComponent("Excel.Application");
    excel.setProperty("Visible", new Variant(true));
    Object workbooks = excel.getProperty("Workbooks").toDispatch();
    Object workbook;

    try {            
        workbook = Dispatch.call((Dispatch)workbooks, "Open", path).toDispatch();           
    } catch (Exception e) {
        showMessageDialog(null,"Unable to open " + path);
        return false;
    }

    try {
        //here you can modify the value of "new Variant(int)" with other number
        Dispatch.call((Dispatch)workbook, "SaveAs", nameFile ,new Variant(2)); 
    } catch (Exception e) {
         showMessageDialog(null,"Unable to convert " + path);
        return false;
    }

    Dispatch.call((Dispatch)workbook, "Close", new Variant(false));

    excel.invoke("Quit", new Variant[0]);
    excel.safeRelease();
    ComThread.Release();

    return true;
}
于 2015-08-28T15:37:41.297 回答
0

如错误所述,它无法找到“FileSaveAs”方法。我试图在 Google/Documentation 中查找它并找不到它(也许它存在但我找不到它)。我找到了 SaveAs。所以尝试使用它,看看会发生什么。

于 2011-09-12T16:49:39.577 回答
0

是的,你是对的,它确实适用于“Saveas”。实际上“FileSaveAs”适用于word文档,所以我想用Excel和Powerpoint尝试一下,但它确实有效......

要另存为 excel 工作簿,此代码有效:

 Dispatch.call(workbook, "SaveAs", filename, new Variant(1)); 
于 2011-09-19T07:29:13.667 回答