使用 QTextDocument::write() 導出 ODT 格式時,表格邊框在 LibreOffice 正常,但在 Microsoft Word 中缺失並報警告。
Microsoft Word 對 ODT 表格邊框支持不完整。官方文檔明確說明:Word 2007 至 2013 僅支持 ODT 表格文本內容,不支持表格框架/邊框屬性。參考:Office 官方差異說明。
在 Linux 下使用 LibreOffice / OpenOffice 打開 ODT,表格邊框完美呈現。適合內部文檔流轉、服務端自動生成報表場景。
#include <QAxObject>
void fixOdtTableBorders(const QString &odtPath) {
QAxObject word("Word.Application");
word.setProperty("Visible", false);
QAxObject *docs = word.querySubObject("Documents");
QAxObject *doc = docs->querySubObject("Open(const QString&)", odtPath);
// 遍歷所有表格設置邊框
QAxObject *tables = doc->querySubObject("Tables");
int count = tables->property("Count").toInt();
for (int i = 1; i <= count; ++i) {
QAxObject *table = tables->querySubObject("Item(int)", i);
QAxObject *borders = table->querySubObject("Borders");
// 設置所有邊框為單實線
for (int b = 1; b <= 6; ++b) { // wdBorderTop...wdBorderHorizontal
QAxObject *border = borders->querySubObject("Item(int)", b);
border->setProperty("LineStyle", 1); // wdLineStyleSingle
border->setProperty("LineWidth", 4); // wdLineWidth075pt
border->setProperty("Color", 0x000000); // 黑色
}
}
doc->dynamicCall("Save()");
doc->dynamicCall("Close()");
word.dynamicCall("Quit()");
}
需在 Windows 安裝 Word,適合最終交付給 Word 用戶的場景。
若無強制 ODT 需求,直接導出 DOCX (OOXML) 或 PDF,兼容性更好,Qt 可通過 QTextDocument::print() 輸出 PDF。