[英]Save Excel file with OLE, Java on Eclipse RCP Application
我嘗試保存一個Excel文件。 Excel文件是帶有makros(* .xltm)的模板。 我可以打開文件並編輯內容,但是如果我嘗試保存目標Excel文件,則該文件已損壞。 我嘗試使用以下方式保存文件:
int id = _workbook.getIDsOfNames(new String[] {"Save"})[0];
_workbook.invoke(id);
或/和
_xlsClientSite.save(_file, true);
您可以嘗試在“保存”呼叫中指定文件格式。
如果幸運的話,您可以在Excel幫助中找到所需的文件格式代碼。 如果找不到所需的內容,則必須使用OLEVIEW.EXE程序弄臟手。 它的副本可能位於您的硬盤驅動器上的某個位置,但是如果沒有,則可以通過快速的Google搜索輕松找到它的副本。
要使用OLEVIEW.EXE :
如果像我一樣使用Office2007(“ Excel12”),則可以嘗試以下值之一:
這是我使用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();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.