使用 Jacob 庫操作 Word 時,呼叫 Dispatch.call(selection, "TypeText", "標題") 報錯:The method call(Dispatch, String, Object[]) ... not applicable for the arguments (Dispatch, String, String)。原因是 Dispatch.call 的第三個參數必須是 Object[] 陣列,而非單一 String。
Dispatch.call(selection, "TypeText", "標題"); // 編譯錯誤
// 將參數包裝為 Object 陣列
Object[] args = new Object[] { "標題" };
Dispatch.call(selection, "TypeText", args);
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordDemo {
public static void main(String[] args) {
ActiveXComponent word = new ActiveXComponent("Word.Application");
try {
word.setProperty("Visible", new Variant(true));
Dispatch documents = word.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(documents, "Add").toDispatch();
Dispatch selection = word.getProperty("Selection").toDispatch();
// 正確呼叫 TypeText
Dispatch.call(selection, "TypeText", new Object[] { "報告標題" });
// 設定字型大小、加粗、置中
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font, "Size", "24");
Dispatch.put(font, "Bold", "True");
Dispatch.put(font, "Name", "微軟正黑體");
Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();
Dispatch.put(alignment, "Alignment", "3"); // wdAlignParagraphCenter
// 儲存並關閉
Dispatch.call(doc, "SaveAs", new Object[] { "C:/demo.docx" });
Dispatch.call(doc, "Close", new Object[] { false });
} finally {
word.invoke("Quit", new Variant[0]);
}
}
}
Dispatch.call(dispatch, methodName, Object[] args):第三參數必須為 Object[],即使只有一個參數。Dispatch.get/put 用於屬性讀寫,參數為 Variant 或基本類型自動裝箱。Dispatch.call(obj, "Release") 或依賴 Jacob 記憶體管理。更多 Jacob 操作 Word 範例可參考:https://www.myexception.cn/program/781772.html
遵循 Object[] 參數規範,即可避免此類編譯錯誤。