0

我尝试保存 Excel 文件。Excel 文件是带有 makros (*.xltm) 的模板。我可以打开文件并编辑内容,但如果我尝试保存目标 Excel 文件已损坏。我尝试使用以下方式保存文件:

int id = _workbook.getIDsOfNames(new String[] {"Save"})[0];
_workbook.invoke(id);

或/和

_xlsClientSite.save(_file, true);
4

1 回答 1

1

您可以尝试在 Save 调用中指定文件格式。

如果幸运的话,您可以在 Excel 帮助中找到所需的文件格式代码。如果在那里找不到所需的东西,则必须使用OLEVIEW.EXE程序亲自动手。它的副本可能位于您的硬盘驱动器某处,但如果没有,通过快速谷歌搜索很容易找到副本。

要使用OLEVIEW.EXE

  • 运行
  • 破解打开“类型库”条目
  • 查找您正在使用的 Excel 版本
  • 打开该项目
  • 搜索为字符串“XlFileFormat”显示的大量文本
  • 检查 XLFileFormat 枚举是否有希望的代码

如果您像我一样使用 Office2007(“Excel12”),您可以尝试以下值之一:

  • xlOpenXMLWorkbookMacroEnabled = 52
  • xlOpenXMLTemplateMacroEnabled = 53

这是我使用 OLE 保存 Excel 文件的一种方法:

/**
 * Save the given workbook in the specified format.
 * 
 * @param controlSiteAuto the OLE control site to use
 * @param filepath the file to save to
 * @param formatCode XlFileFormat code representing the file format to save as
 * @param replaceExistingWithoutPrompt true to replace an existing file quietly, false to ask the user first
 */
public void saveWorkbook(OleAutomation controlSiteAuto, String filepath, Integer formatCode, boolean replaceExistingWithoutPrompt) {
    Variant[] args = null;
    Variant result = null;
    try {
        // suppress "replace existing?" prompt, if necessary
        if (replaceExistingWithoutPrompt) {
            setPropertyOnObject(controlSiteAuto, "Application", "DisplayAlerts", "False");
        }

        // if the given formatCode is null, for some reason, use a reasonable default
        if (formatCode == null) {
            formatCode = 51;    // xlWorkbookDefault=51
        }

        // save the workbook
        int[] id = controlSiteAuto.getIDsOfNames(new String[] {"SaveAs", "FileName", "FileFormat"});
        args = new Variant[2];
        args[0] = new Variant(filepath);
        args[1] = new Variant(formatCode);
        result = controlSiteAuto.invoke(id[0], args);

        if (result == null || !result.getBoolean()) {
            throw new RuntimeException("Unable to save active workbook");
        }

        // enable alerts again, if necessary
        if (replaceExistingWithoutPrompt) {
            setPropertyOnObject(controlSiteAuto, "Application", "DisplayAlerts", "True");
        }
    } finally {
        cleanup(args);
        cleanup(result);
    }
}

protected void cleanup(Variant[] variants) {
    if (variants != null) {
        for (int i = 0; i < variants.length; i++) {
            if (variants[i] != null) {
                variants[i].dispose();
            }
        }
    }
}
于 2013-01-07T16:29:16.240 回答