最近在做编辑器,要读取Word文档,但是QT的QTextEdit没办法直接读取,网上查了好多资料也没有找到解决办法,只好自己动手,现在发出来,给大家提供个方便.(doc和docx格式均可以)
主要原理就是调用Word的
SaveAs方法,要用到QAxWidget调用Word提供的接口
SaveAs方法参数:
SaveAs方法参数说明
QString fileName;//输入一个doc或docx格式文件的路径 例:C:\\hello.doc QAxWidget *a = new QAxWidget("Word.Application");//打开Word a->setControl(fileName);//打开此Word文档 a->setProperty("Visible",false);//设置程序不显示 QVariant newFileName; if(fileName.endsWith(".docx")) { newFileName.setValue(fileName.left(fileName.size()-5).append(".html")); } else if(fileName.endsWith(".doc")){ newFileName.setValue(fileName.left(fileName.size()-4).append(".html")); }
QVariant fileFormat(10); //文件保存格式 HTML文件 这个值有几个枚举类型具体参考:
WdSaveFormat枚举
//下面参数几个默认即可 QVariant LockComments(false);//注释 QVariant Password("");//设置打开密码 QVariant recent(false);//最近打开的文件 QVariant writePassword("");//写入密码 QVariant ReadOnlyRecommended(false);//只读 a->dynamicCall("SaveAs(const QVariant&, const QVariant&,const QVariant&, const QVariant&, const QVariant&, const QVariant&,const QVariant&)",newFileName,fileFormat,LockComments,Password,recent,writePassword,ReadOnlyRecommended); //读取保存后的html文件---编辑结束后即可删除临时生成的html文件 QString newFileName2 = newFileName.toString(); QFile NewFile(newFileName2); NewFile.open(QIODevice::ReadOnly); QTextStream stream(&NewFile); ui->textEdit->setHtml(stream.readAll());