Qt操作Word——在书签处插入表格

    之前做的项目需要用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("检测报告已生成!"));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值