之前做的项目需要用Qt创建并输出word文件作为报告,但是报告格式比较复杂。搜索网上资源后发现,仅凭Qt的API难以实现复杂的格式,尤其是表格嵌套很是麻烦。最后的方案选择用先手动创建word模板,并在固定位置加书签,最后用Qt的API在书签处插入表格,填充数据。网上搜了下未找到在书签处插入表格的方法,自己尝试了下,发现还是可以做到的,样例代码如下:
#include <QAxObject>
#include "qdir.h"
#include "qfiledialog.h"
#include "qdatetime.h"
void outputReport()
{
QString filepath = QFileDialog::getSaveFileName(NULL, QObject::tr("Save Report"),
"/untitled.docx", QObject::tr("Microsoft Word 2007 (*.docx)"));
if (filepath.isNull())
return;
QAxObject word("Word.Application");
word.setProperty("Visible", false);
//获取所有工作文档
QAxObject * documents = word.querySubObject("Documents");
//创建一个word文档
QString sTemp = QDir::currentPath() + QString("ReportTemplate.dotx");
documents->dynamicCall("Add(QString)", sTemp);
QAxObject *document = word.querySubObject("ActiveDocument");
//找到书签位置
QAxObject* bookmark_table = document->querySubObject("Bookmarks(QVariant)",
"dataTable")->querySubObject("Range");
//添加表格
QAxObject* tables = document->querySubObject("Tables");
QVariantList params;
params.append(bookmark_table->asVariant());
params.append(3); //行数
params.append(4); //列数
//表格对象
QAxObject* datatable = tables->querySubObject("Add(QAxObject*, int, int,
QVariant&, QVariant&)", params);
datatable->setProperty("Style", "网格型");
//设置表头
QAxObject* rangeTitle = datatable->querySubObject("Cell(int, int)", 1, 1)->querySubObject("Range");
rangeTitle->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");
rangeTitle->querySubObject("Font")->setProperty("Size", 10.5);
rangeTitle->dynamicCall("SetText(QString)", QStringLiteral("序号"));
rangeTitle = datatable->querySubObject("Cell(int, int)", 1, 2)->querySubObject("Range");
rangeTitle->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");
rangeTitle->querySubObject("Font")->setProperty("Size", 10.5);
rangeTitle->dynamicCall("SetText(QString)", QStringLiteral("测量值"));
rangeTitle = datatable->querySubObject("Cell(int, int)", 1, 3)->querySubObject("Range");
rangeTitle->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");
rangeTitle->querySubObject("Font")->setProperty("Size", 10.5);
rangeTitle->dynamicCall("SetText(QString)", QStringLiteral("理论值"));
document->dynamicCall("SaveAs(const QString&)",
QString(QDir::toNativeSeparators(filepath)));
//关闭文档
document->dynamicCall("Close (boolean)", true);
//退出
word.dynamicCall("Quit (void)");
QMessageBox::about(NULL, QStringLiteral("提示"), QStringLiteral("检测报告已生成!"));
}