赞
踩
使用QAxObject类,需包含头文件#include
pro文件添加模块:QT += axcontainer
新建word文档,另存为.dot格式,在文档中添加书签,这里添加的书签名要在程序里调用,此时添加的书签在文档中不可见,可以选择文件-选项-高级,勾选显示书签
#ifndef WORDENGINE_H #define WORDENGINE_H #include <QObject> #include <QAxObject> class WordEngine : public QObject { Q_OBJECT public: explicit WordEngine(QObject *parent = 0); ~WordEngine(); bool open(bool bVisable = false);//打开文件 bool open(const QString& strFile,bool bVisable = false);//打开文件,重载调用上一个open() bool close();//关闭文件 bool isOpen();//获取文件当前的打开状态 void save();//保存 bool saveAs(const QString& strSaveFile);//另存为文件 bool setMarks(const QString& strMark, const QString& strContent);//设置标签内容 bool setTitle(const QString& strMark, const QString& strContent);//插入word标题 bool setBatchMarks(QStringList &itemList,QStringList sometexts);//批量设置标签内容 void insertTable(int nStart, int nEnd, int row, int column);//插入表格 QAxObject *insertTable(QString sLabel,int row, int column);//在指定标签插入表格 void insertPic(QString sLabel,const QString& picPath);//插入图片 void MergeCells(QAxObject *table, int nStartRow,int nStartCol,int nEndRow,int nEndCol);//合并单元格 void setColumnWidth(QAxObject *table, int column, int width);//设置表格列宽 void setCellString(QAxObject *table, int row, int column, const QString& text);//设置表格内容 void addTableRow(QAxObject *table, int nRow, int rowCount);//为表格添加行 void setCellFontBold(QAxObject *table, int row, int column, bool isBold);//设置表格内容是否为粗体 void setCellFontSize(QAxObject *table, int row, int column, int size);//设置表格字体大小 void insertCellPic(QAxObject *table, int row, int column,const QString& picPath);//在表格中插入图片 signals: public slots: private: bool m_bOpened; QString m_strFilePath; QAxObject *m_wordDocuments; QAxObject *m_wordWidget; }; #endif // WORDENGINE_H
#include "wordengine.h" #include <QDebug> /** * @brief 构造函数 * @param parent 指定父对象 */ WordEngine::WordEngine(QObject *parent) : QObject(parent) ,m_bOpened(false) ,m_wordDocuments(NULL) ,m_wordWidget(NULL) { } /** * @brief 析构函数 */ WordEngine::~WordEngine() { close(); } /** * @brief 打开文件 * @param bVisable 是否显示文件 * @return */ bool WordEngine::open(bool bVisable) { m_wordWidget = new QAxObject(); bool bFlag = m_wordWidget->setControl("word.Application");//初始化COM对象,新建一个word应用程序 if(!bFlag) { bFlag = m_wordWidget->setControl("kwps.Application");//尝试用wps打开 if(!bFlag) return false; } m_wordWidget->setProperty("Visible", bVisable); QAxObject* document = m_wordWidget->querySubObject("Documents");//获取所有的工作文档(返回一个指向QAxObject包含的COM对象) if(!document) return false; document->dynamicCall("Add(QString)",m_strFilePath);//以文件template.dot为模版新建一个文档 m_wordDocuments = m_wordWidget->querySubObject("ActiveDocument");//获取当前激活的文档 m_bOpened = true; return true; } /** * @brief 打开文件,重载,调用上一个open * @param strFilePath 文件路径 * @param bVisable 是否显示文件 * @return */ bool WordEngine::open(const QString &strFilePath, bool bVisable) { m_strFilePath = strFilePath; //close(); return open(bVisable); } /** * @brief 关闭文件 * @return bool */ bool WordEngine::close() { if (m_bOpened) { if(m_wordDocuments) m_wordDocuments->dynamicCall("Close (bool)", true);//关闭文本窗口 if(m_wordWidget) m_wordWidget->dynamicCall("Quit()");//退出word if(m_wordDocuments) delete m_wordDocuments; if(m_wordWidget) delete m_wordWidget; m_bOpened = false; } return m_bOpened; } /** * @brief 获取当前的打开状态 * @return bool */ bool WordEngine::isOpen() { return m_bOpened; } /** * @brief 保存文件 */ void WordEngine::save() { m_wordDocuments->dynamicCall("Save()"); } /** * @brief 另存为文件 * @param strSaveFile 保存路径 * @return */ bool WordEngine::saveAs(const QString &strSaveFile) { return m_wordDocuments->dynamicCall("SaveAs (const QString&)",strSaveFile).toBool(); } /** * @brief 设置标签内容(测试可用) * @param strMark 标签名 * @param strContent 标签内容 * @return */ bool WordEngine::setMarks(const QString &strMark, const QString &strContent) { QAxObject* bookmarkCode = NULL; bookmarkCode = m_wordDocuments->querySubObject("Bookmarks(QVariant)",strMark); //选中标签,将字符textg插入到标签位置 if(bookmarkCode) { bookmarkCode->dynamicCall("Select(void)"); bookmarkCode->querySubObject("Range")->setProperty("Text", strContent); return true; } return false; } /** * @brief 插入标题 3(测试可用) * @param strMark 标签名 * @param strContent 标签内容 * @return */ bool WordEngine::setTitle(const QString &strMark, const QString &strContent) { QAxObject* bookmarkCode = NULL; bookmarkCode = m_wordDocuments->querySubObject("Bookmarks(QVariant)", strMark); //选中标签,将字符textg插入到标签位置 if(bookmarkCode) { bookmarkCode->dynamicCall("Select(void)"); bookmarkCode->querySubObject("Range")->setProperty("Text", strContent+"\n"); //设置该标签为标题3 bookmarkCode->querySubObject("Range")->dynamicCall("SetStyle(QVariant)", QString::fromLocal8Bit("标题 3")); return true; } return false; } /** * @brief 批量设置标签内容 * @param itemList 标签名列表 * @param sometexts 内容列表 * @return */ bool WordEngine::setBatchMarks(QStringList &itemList, QStringList sometexts) { QAxObject* allBookmarks = NULL; allBookmarks = m_wordDocuments->querySubObject("Bookmarks"); //选中标签,将字符text插入到标签位置 if(allBookmarks) { int count = allBookmarks->property("Count").toInt(); /*填写模板中的书签*/ for(int i=count;i>0;--i) { QAxObject *bookmark = allBookmarks->querySubObject("Item(QVariant)", i); QString name= bookmark->property("Name").toString(); int j=0; foreach(QString itemName , itemList) { if (name == itemName) { QAxObject *curBM = m_wordDocuments->querySubObject("Bookmarks(QString)", name); curBM->querySubObject("Range")->setProperty("Text", sometexts.at(j)); break; } j++; } } return true; } return false; } /** * @brief 插入表格(开始和结束位置参数意义不明确) * @param nStart 开始位置 * @param nEnd 结束位置 * @param row 行 * @param column 列 */ void WordEngine::insertTable(int nStart, int nEnd, int row, int column) { QAxObject* ptst = m_wordDocuments->querySubObject( "Range( Long, Long )",nStart, nEnd ); QAxObject* pTable = m_wordDocuments->querySubObject( "Tables" ); QVariantList params; params.append(ptst->asVariant());//转换为QVariant类型的COM对象 params.append(row); params.append(column); if( pTable ) { pTable->dynamicCall( "Add(QAxObject*, Long ,Long )",params); } } /** * @brief 在指定标签插入表格(测试可用) * @param sLabel 标签 * @param row 行 * @param column 列 * @return */ QAxObject *WordEngine::insertTable(QString sLabel,int row, int column) { QAxObject *bookmark = m_wordDocuments->querySubObject("Bookmarks(QVariant)", sLabel); if(bookmark) { bookmark->dynamicCall("Select(void)"); QAxObject *selection = m_wordWidget->querySubObject("Selection"); selection->dynamicCall("InsertAfter(QString&)", "\n"); //selection->dynamicCall("MoveLeft(int)", 1); selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphCenter"); //selection->dynamicCall("TypeText(QString&)", "Table Test");//设置标题 QAxObject *range = selection->querySubObject("Range"); QAxObject *tables = m_wordDocuments->querySubObject("Tables"); QAxObject *table = tables->querySubObject("Add(QVariant,int,int)",range->asVariant(),row,column); for(int i=1;i<=6;i++) { QString str = QString("Borders(-%1)").arg(i); QAxObject *borders = table->querySubObject(str.toLocal8Bit().constData()); borders->dynamicCall("SetLineStyle(int)",1); } return table; } return NULL; } /** * @brief 插入图片 (测试可用) * @param sLabel 标签 * @param picPath 图片路径(绝对路径) */ void WordEngine::insertPic(QString sLabel, const QString &picPath) { QAxObject *bookmark=m_wordDocuments->querySubObject("Bookmarks(QVariant)",sLabel); if(bookmark) { bookmark->dynamicCall("Select(void)"); QAxObject *selection = m_wordWidget->querySubObject("Selection"); selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphCenter"); QAxObject *range = bookmark->querySubObject("Range"); QVariant tmp = range->asVariant(); QList<QVariant>qList; qList<<QVariant(picPath); qList<<QVariant(false); qList<<QVariant(true); qList<<tmp; QAxObject *Inlineshapes = m_wordDocuments->querySubObject("InlineShapes"); Inlineshapes->dynamicCall("AddPicture(const QString&, QVariant, QVariant ,QVariant)",qList); } } /** * @brief 合并单元格(测试可用) * @param table 表 * @param nStartRow 起始行 * @param nStartCol 起始列 * @param nEndRow 终止行 * @param nEndCol 终止列 */ void WordEngine::MergeCells(QAxObject *table, int nStartRow, int nStartCol, int nEndRow, int nEndCol) { QAxObject* StartCell =table->querySubObject("Cell(int, int)",nStartRow,nStartCol); QAxObject* EndCell = table->querySubObject("Cell(int, int)",nEndRow,nEndCol); StartCell->dynamicCall("Merge(LPDISPATCH)",EndCell->asVariant()); } /** * @brief 设置表格列宽 * @param table 表格 * @param column 列数 * @param width 宽度 */ void WordEngine::setColumnWidth(QAxObject *table, int column, int width) { table->querySubObject("Columns(int)", column)->setProperty("Width", width); } /** * @brief 设置表格内容,行和列下标从1开始(测试可用) * @param table表 * @param row 行号 * @param column 列号 * @param text 内容 */ void WordEngine::setCellString(QAxObject *table, int row, int column, const QString &text) { if(table) { table->querySubObject("Cell(int, int)", row, column) ->querySubObject("Range") ->dynamicCall("SetText(QString)", text); } } /** * @brief 为表格添加行 * @param table * @param nRow 插入行 * @param rowCount 插入的行数 */ void WordEngine::addTableRow(QAxObject *table, int nRow, int rowCount) { QAxObject* rows = table->querySubObject("Rows"); int Count = rows->dynamicCall("Count").toInt(); if(0 <= nRow && nRow <=Count) { for(int i = 0; i < rowCount; ++i) { QString sPos = QString("Item(%1)").arg(nRow + i); QAxObject* row = rows->querySubObject(sPos.toStdString().c_str()); QVariant param = row->asVariant(); rows->dynamicCall("Add(Variant)", param); } } } /** * @brief 设置内容是否为粗体(测试可用) * @param table表 * @param row 行号 * @param column 列号 * @param isBold 是否为粗体 */ void WordEngine::setCellFontBold(QAxObject *table, int row, int column, bool isBold) { table->querySubObject("Cell(int, int)",row,column)->querySubObject("Range")->dynamicCall("SetBold(int)", isBold); } /** * @brief 设置字体大小(测试可用) * @param table 表 * @param row 行号 * @param column 列号 * @param size 字体大小 */ void WordEngine::setCellFontSize(QAxObject *table, int row, int column, int size) { table->querySubObject("Cell(int, int)",row,column)->querySubObject("Range")->querySubObject("Font")->setProperty("Size", size); } /** * @brief 在表格中插入图片(测试可用) * @param table 表 * @param row 行号 * @param column 列号 * @param picPath 图片路径 */ void WordEngine::insertCellPic(QAxObject *table, int row, int column, const QString &picPath) { QAxObject* range = table->querySubObject("Cell(int, int)", row, column)->querySubObject("Range"); range->querySubObject("InlineShapes")->dynamicCall("AddPicture(const QString&)", picPath); }
#include "widget.h" #include "ui_widget.h" #include <QDir> #include <QDebug> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); m_pWordEngine = new WordEngine(this); QDir dir("."); QString str = QString("%1/Doc1.dot").arg(dir.absolutePath());//使用绝对路径 m_pWordEngine->open(str,true); m_pWordEngine->setMarks("text",QStringLiteral("一段正文")); m_pWordEngine->setTitle("title",QStringLiteral("一个标题3")); QAxObject* table = m_pWordEngine->insertTable("biaoge",3,5); m_pWordEngine->setCellString(table,1,1,"Hello"); m_pWordEngine->MergeCells(table,1,4,2,4); m_pWordEngine->saveAs(QString("%1/test.doc").arg(dir.absolutePath()));//使用绝对路径 m_pWordEngine->insertPic("image",QString("%1/images/face.jpg").arg(dir.absolutePath())); m_pWordEngine->setCellFontBold(table,1,1,true); m_pWordEngine->setCellFontSize(table,1,1,20); m_pWordEngine->insertCellPic(table,1,2,QString("%1/images/taozi.jpg").arg(dir.absolutePath())); }
程序当前文件夹生成test.doc文件
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。