QDir dir;
QString srcPath, dstPath;
//新建一个word应用程序,并设置为不可见
QAxWidget *word = new QAxWidget("Word.Application");
word->setProperty("Visible", false);
//获取所有的工作文档
QAxObject *documents = new QAxObject;
documents = word->querySubObject("Documents");
//新建一个文档
//documents->dynamicCall("Add(void)");
//以ReportTemplate.docx为模版新建一个文档
srcPath = dir.currentPath() + "/docs/ReportTemplate.docx";
documents->dynamicCall("Add(QString)", srcPath);
//获取当前激活的文档
QAxObject *document = word->querySubObject("ActiveDocument");
//获取文档中的标签并写入
QAxObject *bookmark_code;
QAxObject *selection;
bookmark_code = document->querySubObject("Bookmarks(QVariant)", "Name");//Name是word文档中的标签名
selection = word->querySubObject("Selection");
bookmark_code->querySubObject("Range")->setProperty("Text", querySelected.name);
bookmark_code = document->querySubObject("Bookmarks(QVariant)", "Age");
selection = word->querySubObject("Selection");
bookmark_code->querySubObject("Range")->setProperty("Text", reportAge);
bookmark_code = document->querySubObject("Bookmarks(QVariant)", "Sex");
selection = word->querySubObject("Selection");
bookmark_code->querySubObject("Range")->setProperty("Text", reportSex);
bookmark_code = document->querySubObject("Bookmarks(QVariant)", "Time");
selection = word->querySubObject("Selection");
bookmark_code->querySubObject("Range")->setProperty("Text", reportTime);
bookmark_code = document->querySubObject("Bookmarks(QVariant)", "Assessment");
selection = word->querySubObject("Selection");
bookmark_code->querySubObject("Range")->setProperty("Text", reportAssess);
bookmark_code = document->querySubObject("Bookmarks(QVariant)", "Number");
selection = word->querySubObject("Selection");
bookmark_code->querySubObject("Range")->setProperty("Text", reportID);
bookmark_code = document->querySubObject("Bookmarks(QVariant)", "IPAddr");
selection = word->querySubObject("Selection");
bookmark_code->querySubObject("Range")->setProperty("Text", querySelected.ipAndPort);
bookmark_code = document->querySubObject("Bookmarks(QVariant)", "Operator");
selection = word->querySubObject("Selection");
bookmark_code->querySubObject("Range")->setProperty("Text", querySelected.username);
//写入“hello world”
//selection = word->querySubObject("Selection");
//selection->dynamicCall("TypeText(const QString&)", "hello world");
//设置保存
dstPath = dir.currentPath() + "/" + QString::fromLocal8Bit("测试报告")+".doc";
QVariant newFileName(dstPath);//保存路径及名称
QVariant fileFormat(1);//文件格式
document->dynamicCall("SaveAs(const QVariant&, const QVariant&)", newFileName, fileFormat);
document->dynamicCall("Close (boolean)", true);
word->dynamicCall("Quit(void)");
Qt5编程——word操作
最新推荐文章于 2024-08-03 17:12:27 发布