QString path="C://Users//Admin//Desktop//新建 DOCX 文档.docx";
if(path.isEmpty()==false)//判断路径是否存在path.isEmpty()为空时返回true
{
QFile file(path);
QAxObject *words= new QAxObject(this);//定义一个指针
words->setControl("kwps.Application");//指向wps文件
words->setProperty("Visible",true);//显示对话框setProperty
QAxObject *workbooks = words->querySubObject("Documents");
workbooks->dynamicCall("Add(QString)", path);//链接到具体的文件,path至关重要,获取文件的路径
//打开一个word文件,获取文档
QAxObject *workbook = words->querySubObject("ActiveDocument");//获取word中已经有数值的区域querySubObject
/********修改word中标记书签位置的内容*********/
QString sLabel="XXXXX";//此处必须为文档中被标记为书签的内容,下面语句的意思就是确定书签的位置:
QAxObject *pBookmark = workbook->querySubObject("Bookmarks(QString)",sLabel);//找到活跃区域内的书签querySubObject
//就是把书签内容直接给你替换了
QString sText=ui.textEdit_2->toPlainText();//此处为替换内容
pBookmark->dynamicCall("Select(void)");//选中要选中的区域
pBookmark->querySubObject("Range")->setProperty("Text",sText);//进行替换操作
/*****保存*******/
QString pathsave = QFileDialog::getSaveFileName(this,"Save","../","kwps(*doc)");
if(pathsave.isEmpty()==true)
{
return;
}
workbook->dynamicCall("SaveAs(const QString&))",QDir::toNativeSeparators(pathsave));
//words->setProperty("DisplayAlerts", true);//含有保存的功能,但是无法获得保存的路径,不容易进行下一步操作
workbook->dynamicCall("Close(bool)", true);
words->dynamicCall("Quit()");
delete workbook;
delete words;
file.close();
QMessageBox::warning(this,"完成","文件已经保存",QMessageBox::Yes);