基于
https://blog.csdn.net/qq_35192280/article/details/83021975
进行小调整
.h
#ifndef WORDENGINE_H
#define WORDENGINE_H
#include "corelib_global.h"
#include <QObject>
#include <QAxObject>
#include <QAxWidget>
//#include <QThread>
// https://blog.csdn.net/qq_35192280/article/details/83021975
// Qt 使用QAxObject读取excel和保存excel时,必须保证文件路径是绝对路径,而且需要使用\\分隔符,不能使用/分隔符;
class CORELIB_EXPORT WordEngine : public QObject
{
Q_OBJECT
public:
explicit WordEngine(QObject *parent = nullptr);
WordEngine(const QString& strFile, QObject *parent = nullptr);
~WordEngine();
bool open(bool bVisable = false ,QWidget* mparent=NULL);
bool open(const QString& strFile, bool bVisable = false);
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);
// 批量设置标签
bool setBatchMarks(QStringList &strItemList, QStringList strList);
// 创建表格
void insertTable(int nStart, int nEnd, int row, int column);
QAxObject *insertTable(QString sLabel, int row, int column);
//合并单元格
void MergeCells(QAxObject *table, int nStartRow, int nStartCol, int nEndRow, int nEndCol);
// 拆分单元格
void SplitCell(QAxObject *table, int nStartRow, int nStartCol, int nEndRow, int nEndCol);
//插入图片
void insertPic(QString sLabel, const QString& strPicPath);
//设置列宽
void setColumnWidth(QAxObject *table, int column, int width);
// 设置行高
void setTableRowHeight(QAxObject *table, int row, int height);
// 设置表格内容
void setCellString(QAxObject *table, int row, int column, const QString& text);
// 为表格添加行
void addTableRow(QAxObject *table, int nRow, int rowCount);
void addTableRow(QAxObject *table);
// 设置内容粗体 isBold控制是否粗体
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& strPicPath);
// 设置对齐方式 0-左对齐 1居中 2右对齐
void setAlign(QAxObject* selection, int nAlign);
QAxObject *queryTable();
QAxObject *getTable(int nIndex, int& nRowCount, int& nColCount);
// 打印
void printDoc();
void printDoc(int nPageFrom, int nPageTo);
private:
bool m_bOpened = false;
QString m_strFilePath;
QAxObject *m_pDoc = nullptr;
QAxWidget *m_wordWidget = nullptr;
signals:
public slots:
};
#endif // WORDENGINE_H
.cpp
#include "WordEngine.h"
#include "wordengine.h"
#include "qt_windows.h"
#include <QDir>
//#include <QDebug>
WordEngine::WordEngine(QObject *parent) :
QObject(parent),
m_bOpened(false),
m_pDoc(nullptr),
m_wordWidget(nullptr)
{
}
WordEngine::WordEngine(const QString& strFilePath, QObject *parent) :
QObject(parent),
m_bOpened(false),
m_strFilePath(strFilePath),
m_pDoc(nullptr),
m_wordWidget(nullptr)
{
}
WordEngine::~WordEngine()
{
close();
}
/******************************************************************************
* 函数:open
* 功能:打开文件
* 参数:bVisable 是否显示弹窗
* 返回值: bool
*****************************************************************************/
bool WordEngine::open(bool bVisable, QWidget* mparent)
{
//新建一个word应用程序,并设置为可见
m_wordWidget = new QAxWidget(mparent);
bool bFlag = m_wordWidget->setControl("word.Application");
if (!bFlag)
{
// 用wps打开
bFlag = m_wordWidget->setControl("kwps.Application");
if (!bFlag)
return false;
}
m_wordWidget->setProperty("Visible", bVisable);
//获取所有的工作文档
QAxObject *document = m_wordWidget->querySubObject("Documents");
if (!document)
{
return false;
}
//以文件template.dot为模版新建一个文档
document->dynamicCall("Add(QString)", m_strFilePath);
//获取当前激活的文档
m_pDoc = m_wordWidget->querySubObject("ActiveDocument");
if (m_pDoc)
m_bOpened = true;
return m_bOpened;
}
/******************************************************************************
* 函数:open
* 功能:打开文件
* 参数:strFilePath 文件路径;bVisable 是否显示弹窗
* 返回值:bool
*****************************************************************************/
bool WordEngine::open(const QString& strFilePath, bool bVisable)
{
m_strFilePath = strFilePath;
close();
return open(bVisable);
}
/******************************************************************************
* 函数:close
* 功能:关闭文件
* 参数:无
* 返回值:bool
*****************************************************************************/
bool WordEngine::close()
{
if (m_bOpened)
{
if (m_pDoc)
m_pDoc->dynamicCall("Close (bool)", true);//关闭文本窗口
if (m_wordWidget)
m_wordWidget->dynamicCall("Quit()");//退出word
if (m_pDoc)
delete m_pDoc;
if (m_wordWidget)
delete m_wordWidget;
m_bOpened = false;
}
return m_bOpened;
}
/******************************************************************************
* 函数:isOpen
* 功能:获得当前的打开状态
* 参数:无
* 返回值:bool
*****************************************************************************/
bool WordEngine::isOpen()
{
return m_bOpened;
}
/******************************************************************************
* 函数:save
* 功能:保存文件
* 参数:无
* 返回值:void
*****************************************************************************/
void WordEngine::save()
{
if (m_pDoc)
m_pDoc->dynamicCall("Save()");
}
/******************************************************************************
* 函数:saveAs
* 功能:另存文件
* 参数:strSaveFile 文件路径
* 返回值:void
*****************************************************************************/
bool WordEngine::saveAs(const QString& strSaveFile)
{
QDir dir(strSaveFile);
QString strTemp = dir.absolutePath();
strTemp = QDir::toNativeSeparators(strTemp);
if (m_pDoc)
m_pDoc->dynamicCall("SaveAs (const QString&)", strTemp).toBool();
return true;
}
/******************************************************************************
* 函数:setMarks
* 功能:设置标签内容
* 参数:strMark 标签名;strContent 文本
* 返回值:bool
*****************************************************************************/
bool WordEngine::setMarks(const QString& strMark, const QString& strContent)
{
if (!m_pDoc)
return false;
QAxObject* bookmarkCode = nullptr;
bookmarkCode = m_pDoc->querySubObject("Bookmarks(QVariant)", strMark);
//选中标签,将字符textg插入到标签位置
if (bookmarkCode)
{
bookmarkCode->dynamicCall("Select(void)");
bookmarkCode->querySubObject("Range")->setProperty("Text", strContent);
return true;
}
return false;
}
/******************************************************************************
* 函数:setTitle
* 功能:插入标题 3
* 参数:strMark 标签名;strContent 文本
* 返回值:bool
*****************************************************************************/
bool WordEngine::setTitle(const QString& strMark, const QString& strContent)
{
if (!m_pDoc)
return false;
QAxObject* bookmarkCode = nullptr;
bookmarkCode = m_pDoc->querySubObject("Bookmarks(QVariant)", strMark);
//选中标签,将字符textg插入到标签位置
if (bookmarkCode)
{
bookmarkCode->dynamicCall("Select(void)");
bookmarkCode->querySubObject("Range")->setProperty("Text", strContent + "\n");
bookmarkCode->querySubObject("Range")->dynamicCall("SetStyle(QVariant)", QString::fromLocal8Bit("标题 3"));
return true;
}
return false;
}
/******************************************************************************
* 函数:setBatchMarks
* 功能:批量设置标签内容
* 参数:itemList 标签名列表;sometexts 内容列表
* 返回值:bool
*****************************************************************************/
bool WordEngine::setBatchMarks(QStringList &strItemList, QStringList strList)
{
if (!m_pDoc)
return false;
QAxObject* allBookmarks = nullptr;
allBookmarks = m_pDoc->querySubObject("Bookmarks");
//选中标签,将字符textg插入到标签位置
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;
for(QString strItem : strItemList)
{
if (name == strItem)
{
QAxObject *curBM = m_pDoc->querySubObject("Bookmarks(QString)", name);
if (curBM)
curBM->querySubObject("Range")->setProperty("Text", strList.at(j));
break;
}
j++;
}
return true;
}
return false;
}
return false;
}
/******************************************************************************
* 函数:insertTable
* 功能:创建表格
* 参数:nStart 开始位置; nEnd 结束位置; row 行; column 列
* 返回值: void
*****************************************************************************/
void WordEngine::insertTable(int nStart, int nEnd, int row, int column)
{
if (!m_pDoc)
return;
QAxObject* ptst = m_pDoc->querySubObject("Range( Long, Long )", nStart, nEnd);
QAxObject* pTable = m_pDoc->querySubObject("Tables");
if (!ptst || !pTable)
return;
QVariantList params;
params.append(ptst->asVariant());
params.append(row);
params.append(column);
pTable->dynamicCall("Add(QAxObject*, Long ,Long )", params);
}
QAxObject *WordEngine::insertTable(QString sLabel, int row, int column)
{
if (!m_pDoc)
return nullptr;
QAxObject *bookmark = m_pDoc->querySubObject("Bookmarks(QVariant)", sLabel);
if (bookmark)
{
bookmark->dynamicCall("Select(void)");
QAxObject *selection = m_wordWidget->querySubObject("Selection");
if (!selection)
return nullptr;
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_pDoc->querySubObject("Tables");
QAxObject *table = tables->querySubObject("Add(QVariant,int,int)", range->asVariant(), row, column);
if (!tables)
return nullptr;
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 nullptr;
}
/******************************************************************************
* 函数:insertPic
* 功能:插入图片
* 参数:sLable 标签名;picPath 图片路径
* 返回值:void
*****************************************************************************/
void WordEngine::insertPic(QString sLabel, const QString& strPicPath)
{
if (!m_pDoc)
return;
QAxObject *bookmark = m_pDoc->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");
if (!range)
return;
QVariant tmp = range->asVariant();
QList<QVariant>qList;
QDir dir(strPicPath);
QString strTemp = dir.absolutePath();
strTemp = QDir::toNativeSeparators(strTemp);
qList << QVariant(strTemp);
qList << QVariant(false);
qList << QVariant(true);
qList << tmp;
QAxObject *Inlineshapes = m_pDoc->querySubObject("InlineShapes");
if (Inlineshapes)
Inlineshapes->dynamicCall("AddPicture(const QString&, QVariant, QVariant ,QVariant)", qList);
}
}
/******************************************************************************
* 函数:MergeCells
* 功能:合并单元格
* 参数:table 表格; nStartRow 起始单元格行数; nStartCol ; nEndRow ; nEndCol
* 返回值:void
*****************************************************************************/
void WordEngine::MergeCells(QAxObject *table, int nStartRow, int nStartCol, int nEndRow, int nEndCol)
{
if (table)
{
QAxObject* StartCell = table->querySubObject("Cell(int, int)", nStartRow, nStartCol);
QAxObject* EndCell = table->querySubObject("Cell(int, int)", nEndRow, nEndCol);
if (StartCell || EndCell)
StartCell->dynamicCall("Merge(LPDISPATCH)", EndCell->asVariant());
}
}
// https://www.codeleading.com/article/55712440278/
void WordEngine::SplitCell(QAxObject *table, int nStartRow, int nStartCol, int nEndRow, int nEndCol)
{
if (table)
{
QAxObject* StartCell = table->querySubObject("Cell(int, int)", nStartRow, nStartCol);
if (StartCell)
{
StartCell->querySubObject("Split(int,int)", nEndRow, nEndCol);
}
}
}
/******************************************************************************
* 函数:setColumnWidth
* 功能:设置表格列宽
* 参数:table 表格; column 列数; width 宽度
* 返回值:void
*****************************************************************************/
void WordEngine::setColumnWidth(QAxObject *table, int column, int width)
{
if (table)
table->querySubObject("Columns(int)", column)->setProperty("Width", width);
}
/******************************************************************************
* 函数:设置行高
* 功能:设置表格列宽
* 参数:table 表格; row 行; height 宽度
* 返回值:void
*****************************************************************************/
void WordEngine::setTableRowHeight(QAxObject *table, int row, int height)
{
if (table)
{
QAxObject* cell = table->querySubObject("Cell(int, int)", row, 1);
cell->setProperty("HeightRule", "wdRowHeightExactly");//wdRowHeightAtLeast wdRowHeightExactly wdRowHeightAuto
if (cell)
cell->setProperty("Height", height);
}
}
/******************************************************************************
* 函数:setCellString
* 功能:设置表格内容
* 参数:table 表格; row 行数; column 列数; text 插入文本
* 返回值:void
*****************************************************************************/
void WordEngine::setCellString(QAxObject *table, int row, int column, const QString& text)
{
if (table)
{
QAxObject* pCell = table->querySubObject("Cell(int, int)", row, column);
if (pCell)
{
QAxObject* pRange = pCell->querySubObject("Range");
if (pRange)
pRange->dynamicCall("SetText(QString)", text);
}
}
}
/******************************************************************************
* 函数:addTableRow
* 功能:为表格添加行
* 参数:table 表格; nRow 插入行; rowCount 插入的行数
* 返回值:void
*****************************************************************************/
void WordEngine::addTableRow(QAxObject *table, int nRow, int rowCount)
{
if (table)
{
QAxObject* rows = table->querySubObject("Rows");
if (!rows)
return;
int Count = rows->dynamicCall("Count").toInt();
//nRow = Count ;
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());
if (row)
{
QVariant param = row->asVariant();
rows->dynamicCall("Add(Variant)", param);
}
}
}
}
}
void WordEngine::addTableRow(QAxObject *table)
{
QAxObject* rows = table->querySubObject("Rows");
if (!rows)
return;
int Count = rows->dynamicCall("Count").toInt();
QAxObject* row = rows->querySubObject("Item(int)", Count);
if (row)
{
QVariant param = row->asVariant();
rows->dynamicCall("Add(Variant)", param);
}
}
/******************************************************************************
* 函数:setCellFontBold
* 功能:设置内容粗体 isBold控制是否粗体
* 参数:table 表格; row 插入行; column 列数; isBold 是否加粗
* 返回值:void
*****************************************************************************/
void WordEngine::setCellFontBold(QAxObject *table, int row, int column, bool isBold)
{
if (table)
table->querySubObject("Cell(int, int)", row, column)
->querySubObject("Range")->dynamicCall("SetBold(int)", isBold);
}
/******************************************************************************
* 函数:setCellFontSize
* 功能:设置文字大小
* 参数:table 表格; row 插入行; column 列数; size 字体大小
* 返回值:void
*****************************************************************************/
void WordEngine::setCellFontSize(QAxObject *table, int row, int column, int size)
{
if (table)
table->querySubObject("Cell(int, int)", row, column)->querySubObject("Range")
->querySubObject("Font")->setProperty("Size", size);
}
/******************************************************************************
* 函数:insertCellPic
* 功能:在表格中插入图片
* 参数:table 表格; row 插入行; column 列数; picPath 图片路径
* 返回值:void
*****************************************************************************/
void WordEngine::insertCellPic(QAxObject *table, int row, int column, const QString& strPicPath)
{
if (table)
{
QDir dir(strPicPath);
QString strTemp = dir.absolutePath();
strTemp = QDir::toNativeSeparators(strTemp);
QAxObject* range = table->querySubObject("Cell(int, int)", row, column)
->querySubObject("Range");
range->querySubObject("InlineShapes")
->dynamicCall("AddPicture(const QString&)", strTemp);
}
}
void WordEngine::setAlign(QAxObject* selection, int nAlign)
{
if (!selection)
return;
switch (nAlign)
{
case 0:
selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphLeft");
break;
case 1:
selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphCenter");
break;
case 2:
selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphRight");
break;
}
}
#include <QDebug>
QAxObject * WordEngine::queryTable()
{
if (nullptr == m_pDoc)
return nullptr;
QAxObject* tables = m_pDoc->querySubObject("Tables"); //获取所有表格
//QAxBase::PropertyBag p = m_document->propertyBag();
int tablecount = 1;
if (nullptr != tables)
{
tablecount = tables->dynamicCall("Count").toInt(); //获取表格个数
delete tables;
tables = nullptr;
}
for (int i = 1; i < tablecount + 1; ++i)
{
QAxObject *table = m_pDoc->querySubObject("Tables(int)", i); //获取某个表格
if (nullptr == table)
continue;
int rowCount = table->querySubObject("Rows")->dynamicCall("Count").toInt();
int colCount = table->querySubObject("Columns")->dynamicCall("Count").toInt();
QAxBase::PropertyBag p = table->propertyBag();
for (int row = 1; row < rowCount + 1; ++row)
{
for (int col = 1; col < colCount + 1; ++col)
{
QAxObject *cell = table->querySubObject("Cell(int,int)", row, col); //获取表格数据
if (nullptr == cell)
continue;
QString sp = cell->querySubObject("Range")->property("Text").toString();
qDebug() << row << " " << col << " " << sp;
delete cell;
cell = nullptr;
}
}
delete table;
table = nullptr;
}
return tables;
}
QAxObject * WordEngine::getTable(int nIndex, int& nRowCount, int& nColCount)
{
if (nullptr == m_pDoc)
return nullptr;
QAxObject* tables = m_pDoc->querySubObject("Tables"); //获取所有表格
if (nullptr == tables)
return nullptr;
int nTableCount = 1;
nTableCount = tables->dynamicCall("Count").toInt(); //获取表格个数
delete tables;
tables = nullptr;
if (nIndex > nTableCount)
return nullptr;
QAxObject *table = m_pDoc->querySubObject("Tables(int)", nIndex); //获取某个表格
if (table)
{
nRowCount = table->querySubObject("Rows")->dynamicCall("Count").toInt();
nColCount = table->querySubObject("Columns")->dynamicCall("Count").toInt();
return table;
}
return nullptr;
}
void WordEngine::printDoc()
{
if (m_pDoc)
m_pDoc->dynamicCall("PrintOut()");
}
void WordEngine::printDoc(int nPageFrom, int nPageTo)
{
QList<QVariant> vars;
vars.push_back(QVariant(true)); //background
vars.push_back(QVariant(false)); //append
vars.push_back(QVariant("wdPrintRangeOfPages")); //range
vars.push_back(QVariant("")); //OutputFileName
vars.push_back(QVariant(nPageFrom)); //From
vars.push_back(QVariant(nPageTo)); //To
vars.push_back(QVariant("_wdPrintDocumentContent")); //Item
vars.push_back(QVariant(1)); //Copy
vars.push_back(QVariant("1")); //Pages
vars.push_back(QVariant("_wdPrintAllPages")); //PageType
vars.push_back(QVariant(false)); //PrintToFile
vars.push_back(QVariant(true)); //Collate
vars.push_back(QVariant("")); //FileName
vars.push_back(QVariant(false)); //ManualDuplexPrint
vars.push_back(QVariant(0)); //PrintZoomCulumn
vars.push_back(QVariant(0)); //PrintZoomRow
vars.push_back(QVariant(0)); //PrintZoomPaperWidth
vars.push_back(QVariant(0)); //PrintZoomPaperHeight
m_pDoc->dynamicCall("PrintOut(bool,bool,const QString&,const QString&,\
int,int,const QString&,int,const QString&,const QString&,bool,bool,\
const QString&,bool,int,int,int,int)", vars);
}