QT技术实现Word模板编辑及转PDF

这篇具有很好参考价值的文章主要介绍了QT技术实现Word模板编辑及转PDF。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

本文分享基于QT进行Word模板编辑以及Word转PDF的技术,希望对各位小伙伴有所帮助!


1. 制作Word模板-添加书签

        》新建Word文档

        》插入---标签

                将待插入内容制作为标签

        》保存为.dot格式

2. 基于QT编辑Word模板

        》书签 替换为 文本

    //新建一个word应用程序
    QAxWidget* word = new QAxWidget("Word.Application", 0, Qt::MSWindowsOwnDC);
    //并设置为不可见
    word->setProperty("Visible", false);
    //获取所有的工作文档
    QAxObject* documents = word->querySubObject("Documents");
    //以test2.dot为模板新建一个文档
    documents->dynamicCall("Add(QString)", strTemplatePath);
    //获取当前激活的文档
    QAxObject* document = word->querySubObject("ActiveDocument");

    //获取文档中名字为name的标签
    QAxObject* bookmark_name = document->querySubObject("Bookmarks(QVariant)", "name");
    //选中标签,将字符textg插入到标签位置
    if (!bookmark_name->isNull())
    {
        QString sText = ui->lineEdit_name->text();                          //此处为替换内容
        
        bookmark_name->dynamicCall("Select(void)");                             //选中要选中的区域
        bookmark_name->querySubObject("Range")->setProperty("Text", sText);      //进行替换操作
    }

    //获取文档中名字为sex的标签
    QAxObject* bookmark_sex = document->querySubObject("Bookmarks(QVariant)", "sex");
    //选中标签,将字符textg插入到标签位置
    if (!bookmark_sex->isNull())
    {
        QString sText = ui->lineEdit_sex->text();                          //此处为替换内容

        bookmark_sex->dynamicCall("Select(void)");                             //选中要选中的区域
        bookmark_sex->querySubObject("Range")->setProperty("Text", sText);      //进行替换操作
    }


    //将文件保存为doc,同样可以生成docx文档
    QString pathsave = QApplication::applicationDirPath() + QString::fromLocal8Bit("\\Report\\report_template.docx");
    if (pathsave.isEmpty() == true)
    {
        return;
    }
    document->dynamicCall("SaveAs(const QString&))", QDir::toNativeSeparators(pathsave));
    document->dynamicCall("Close (boolean)", false);
    

    word->dynamicCall("Quit()");
    QMessageBox::warning(this, "完成", "文件已经保存", QMessageBox::Yes);

        》书签 替换为 图片

bool insertPic(QAxObject* document, QString sLabel, QString sFile)
{
    if (!document)
        return false;

    QAxObject* bookmark_pic = document->querySubObject("Bookmarks(QString)", sLabel);
    if (bookmark_pic)
    {
        bookmark_pic->dynamicCall("Select(void)");
        QAxObject* range = bookmark_pic->querySubObject("Range");
        QVariant tmp = range->asVariant();
        QList<QVariant> qList;
        qList << QVariant(sFile);
        qList << QVariant(false);
        qList << QVariant(true);
        qList << tmp;
        QAxObject* Inlineshapes = document->querySubObject("InlineShapes");
        Inlineshapes->dynamicCall("AddPicture(const QString&,QVariant,QVariant,QVariant)", qList);
        delete Inlineshapes;
    }
    return true;
}

3. Word转PDF

void zxKneeReportWidget::convertToPDF(QString strWordPath, QString strTargetPath)
{
    if (strWordPath.isEmpty() || strTargetPath.isEmpty()) return;

    QAxObject* pWordApplication = new QAxObject("Word.Application", 0);
    QAxObject* pWordDocuments = pWordApplication->querySubObject("Documents");

    QString fileName = strWordPath;
    QString toFilePath = strTargetPath;

    QVariant filename(fileName);
    QVariant confirmconversions(false);
    QVariant readonly(true);
    QVariant addtorecentfiles(false);
    QVariant passworddocument("");
    QVariant passwordtemplate("");
    QVariant revert(false);
    //打开
    QAxObject* doc = pWordDocuments->querySubObject("Open(const QVariant&, const QVariant&,const QVariant&, "
        "const QVariant&, const QVariant&, "
        "const QVariant&,const QVariant&)",
        filename,
        confirmconversions,
        readonly,
        addtorecentfiles,
        passworddocument,
        passwordtemplate,
        revert);

    QVariant OutputFileName(toFilePath);
    QVariant ExportFormat(17);      //17是pdf
    QVariant OpenAfterExport(false); //保存后是否自动打开
    //转成pdf
    doc->querySubObject("ExportAsFixedFormat(const QVariant&,const QVariant&,const QVariant&)",
        OutputFileName,
        ExportFormat,
        OpenAfterExport
    );

    //关闭
    doc->dynamicCall("Close(boolean)", false);
}

4. 其它Word操作

/*
* 排版方式
* 纵行、横行
*/

void WordEngine::setype(bool type)
{
	QAxObject* selection = m_pWord->querySubObject("Selection");
	if (!selection)
	{
		return;
	}
	if (type)
	{
		selection->querySubObject("PageSetup")->setProperty("Orientation", "wdOrientLandscape");
	}
	else {
		selection->querySubObject("PageSetup")->setProperty("Orientation", "wdOrientPortrait");
	}
}

/*
* 获取页宽
*/

int WordEngine::pageWidth()
{
	int width;
	QAxObject* selection = m_pWord->querySubObject("Selection");
	if (!selection)
	{
		return width;
	}
	width = selection->querySubObject("PageSetup")->property("PageWidth").toInt();;
	return width;
}

/*
*设置字号
*/

void WordEngine::setFontSize(int size)
{
	QAxObject* selection = m_pWord->querySubObject("Selection");
	if (!selection)
	{
		return;
	}
	selection->querySubObject("Font")->setProperty("Size", size);
}

/*
设置对齐方式
*/

void WordEngine::setAlignment(int index)
{
	QAxObject *selection = m_pWord->querySubObject("Selection");
	if (!selection)
	{
		return;
	}
	if (index == 0)
	{
		selection->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");
	}
	if (index == 1)
	{
		selection->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphJustify");
	}
	if (index == 2)
	{
		selection->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphRight");
	}
	if (index == 3)
	{
		selection->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphLeft");
	}
}


/*
插入文字
*/

void WordEngine::typeText(QString text, int index, int WdBuiltinStyle, bool bold, int size)
{
	QAxObject* selection = m_pWord->querySubObject("Selection");
	if (!selection)
	{
		return;
	}
	setAlignment(index);
	setFontSize(size);
	if (bold)
		selection->querySubObject("Range")->dynamicCall("SetBold(int)", true);
	//if(WdBuiltinStyle==0)
	//	selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleBodyText");
	if(WdBuiltinStyle==1)
	    selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleHeading1");
	else if (WdBuiltinStyle == 2)
		selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleHeading2");
	else if (WdBuiltinStyle == 3)
		selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleHeading3");
	else if (WdBuiltinStyle == 4)
		selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleHeading4");
	selection->dynamicCall("TypeText(const QString&)", text);
}
/*
插入图片
*/

void WordEngine::AddPicture(QString file)
{
	QAxObject* selection = m_pWord->querySubObject("Selection");
	if (!selection)
	{
		return;
	}
	setAlignment(0);
	QString filename = file;
	filename.replace("/", "\\");
	QAxObject *Inlineshapes = selection->querySubObject("InlineShapes");
	Inlineshapes->dynamicCall("AddPicture(const QString&)", filename);
	delete Inlineshapes;
}

/*
插入回车
*/

void WordEngine::insertEnter()
{
	QAxObject* selection = m_pWord->querySubObject("Selection");
	if (!selection)
	{
		return;
	}
	selection->dynamicCall("TypeParagraph(void)");
}

/*
* 光标移到末尾,跳出单元格
*/
void WordEngine::moveForEnd()
{
	QAxObject* selection = m_pWord->querySubObject("Selection");
	QVariantList params;
	params.append(6);
	params.append(0);
	selection->dynamicCall("EndOf(QVariant&, QVariant&)", params).toInt();
}

/*
创建表格
QStringList headList 添加表头
*/

QAxObject* WordEngine::createTable(int row, int column, QStringList headList,bool SetLineStyleHide)
{
	QAxObject* selection = m_pWord->querySubObject("Selection");
	if (!selection)
	{
		return false;
	}
	selection->dynamicCall("InsertAfter(QString&)", "\r\n");

	QAxObject *range = selection->querySubObject("Range");
	QAxObject *tables = m_pWorkDocument->querySubObject("Tables");
	QAxObject *table = tables->querySubObject("Add(QVariant,int,int)", range->asVariant(), row, column);

	table->setProperty("Style", "网格型");
	//表格自动拉伸列 0固定  1根据内容调整  2 根据窗口调整
	table->dynamicCall("AutoFitBehavior(WdAutoFitBehavior)", 2);

	//设置表头
	for (int i = 0; i<headList.size(); i++)
	{
		table->querySubObject("Cell(int,int)", 1, i + 1)->querySubObject("Range")->dynamicCall("SetText(QString)", headList.at(i));
		//加粗
		table->querySubObject("Cell(int,int)", 1, i + 1)->querySubObject("Range")->dynamicCall("SetBold(int)", true);
		table->querySubObject("Cell(int,int)", 1, i + 1)->querySubObject("Font")->setProperty("Size", 10);
	}
	if (!SetLineStyleHide)
	{
		for (int i = 1; i <= 6; i++)
		{
			QString str = QString("Borders(-%1)").arg(i);
			QAxObject *borders = table->querySubObject(str.toLatin1().constData());
			borders->dynamicCall("SetLineStyle(int)", 1);
		}
	}
	return table;
}

/*
填充表格
*/

void WordEngine::setCellText(QAxObject *table, int row, int column, QString text)
{
	QAxObject* range = table->querySubObject("Cell(int, int)", row + 1, column + 1)->querySubObject("Range");
	if (range)
	{
		return;
	}

	range->dynamicCall("SetText(QString)", text);
}

/*
表格插入图片
*/
void WordEngine::setAddPicture(QAxObject *table, int row, int column, QString picPath)
{
	QAxObject* range = table->querySubObject("Cell(int, int)", row + 1, column + 1)->querySubObject("Range");
	if (!range)
	{
		return;
	}
	range->querySubObject("InlineShapes")->dynamicCall("AddPicture(const QString&)", picPath);
}

/*
光标跳转,类似表格中的tab
*/

void WordEngine::moveRight()
{
	QAxObject* selection = m_pWord->querySubObject("Selection");
	if (!selection)
	{
		return;
	}
	selection->dynamicCall("MoveRight(int)", 1);
}

/*****标签处添加字符串
******input:(QString)word模板地址,(bool)生成word文档是否可视
******output:
*/
bool WordEngine::Open(QString sFile, bool bVisible)
{
	//新建一个word应用程序
	m_pWord = new QAxObject();
	bool bFlag = m_pWord->setControl("word.Application");
	if (!bFlag)
	{
		return false;
	}
	QObject::connect(m_pWord, SIGNAL(exception(int, QString, QString, QString)),
		this, SLOT(saveLastError(int, QString, QString, QString)));
	m_pWord->setProperty("Visible", bVisible);
	//获取所有的工作文档
	QAxObject *document = m_pWord->querySubObject("Documents");
	if (!document)
	{
		return false;
	}
	//以文件template.dot为模版新建一个文档
	document->dynamicCall("Add(QString)", sFile);
	//获取当前激活的文档
	m_pWorkDocument = m_pWord->querySubObject("ActiveDocument");
	if (m_pWorkDocument)
		m_bIsOpen = true;
	else
		m_bIsOpen = false;

	return m_bIsOpen;
}
/*****标签处添加字符串
******input:(QString)保存地址
******output:
*/
void WordEngine::save(QString sSavePath)
{
	if (m_bIsOpen && m_pWorkDocument)
	{
		if (m_bNewFile) {
			m_pWorkDocument->dynamicCall("Save()");
		}
		else {
			//m_pWorkDocument->dynamicCall("SaveAs (const QString&,int,const QString&,const QString&,bool,bool)",
			//                           m_sFile,56,QString(""),QString(""),false,false);
			m_pWorkDocument->dynamicCall("SaveAs (const QString&)", sSavePath);
		}
	}
	qDebug() << "save Done.";
}
/*****标签处添加字符串
******input:(bool)是否保存当前文件,(QString)保存地址[必填]
******output:
*/
void WordEngine::close(bool bSave,QString save_path)
{
	if (bSave) {
		save(save_path);
	}
	if (m_pWord) {
		m_pWord->setProperty("DisplayAlerts", true);
	}
	if (m_pWorkDocument) {
		m_pWorkDocument->dynamicCall("Close(bool)", true);
	}
	if (m_pWord) {
		m_pWord->dynamicCall("Quit()");
	}
	if (m_pWorkDocuments)
	{
		delete m_pWorkDocuments;
	}
	if (m_pWord)
	{
		delete m_pWord;
	}
	m_pWorkDocument = NULL;
	m_pWorkDocuments = NULL;
	m_pWord = NULL;

	m_bIsOpen = false;
	m_bNewFile = false;
}
/*****标签处添加字符串
******input:(QString)标签名字,(QString)内容
******output: (bool)
*/
bool WordEngine::replaceText(QString sLabel, QString sText)
{
	if (!m_pWorkDocument) {
		return false;
	}
	//获取文档中名字为sLabel的标签
	QAxObject *pBookmark = m_pWorkDocument->querySubObject("Bookmarks(QString)", sLabel);
	if (pBookmark)
	{
		pBookmark->dynamicCall("Select(void)");
		pBookmark->querySubObject("Range")->setProperty("Text", sText);
		delete pBookmark;
	}
	return true;
}
/***** 插入文本到标签处 【 居中,行距1.5,段后0.5】
******input:(QString)标签名字,(QString)内容,(QString)字体,(int)字体大小 【默认黑体,字号12】
******output: (bool)
*/
bool WordEngine::replaceTextStyle(QString sLabel, QString sText, QString FontName, int size)
{
	if (!m_pWorkDocument) {
		return false;
	}
	//获取文档中名字为sLabel的标签
	QAxObject *pBookmark = m_pWorkDocument->querySubObject("Bookmarks(QString)", sLabel);
	if (pBookmark)
	{

		pBookmark->dynamicCall("Select(void)");

		QAxObject *selection = m_pWord->querySubObj## 标题ect("Selection");//设置字体FontName
		selection->dynamicCall("InsertAfter(QString&)", "\r\n");//不能删除,否则会出错
		selection->querySubObject("Range")->querySubObject("Font")->setProperty("Size", size);//设置字体大小:小四12
		selection->querySubObject("Range")->querySubObject("Font")->setProperty("Name", FontName);//字体(在插入字符前设置字体)

		pBookmark->querySubObject("Range")->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");//水平居中
		pBookmark->querySubObject("Range")->querySubObject("ParagraphFormat")->setProperty("LineSpacingRule", "wdLineSpace1pt5");//1.5行距  
		pBookmark->querySubObject("Range")->querySubObject("ParagraphFormat")->setProperty("LineUnitAfter", 0.5);//段后0.5
		pBookmark->querySubObject("Range")->setProperty("Text", sText);//插入字符
		delete pBookmark;
		//selection->querySubObject("Range")->querySubObject("Font")->setProperty("Bold", 1);//加粗
	}
	return true;
}
/***** 插入文本到标签处 【 居中,行距1.5,段后0.5】
******input:(QString)标签名字,(QString)内容,是否居中(0靠左,1居中,2靠右),(QString)字体,(int)字体大小 【默认黑体,字号12】
******output: (bool)
*/
bool WordEngine::WordReplaceText(QString sLabel, QString sText, int iscenter, QString FontName, int size)
{
	if (!m_pWorkDocument) {
		return false;
	}
	//获取文档中名字为sLabel的标签
	QAxObject *pBookmark = m_pWorkDocument->querySubObject("Bookmarks(QString)", sLabel);
	if (pBookmark)
	{

		pBookmark->dynamicCall("Select(void)");

		QAxObject *selection = m_pWord->querySubObject("Selection");//设置字体FontName
		selection->dynamicCall("InsertAfter(QString&)", "\r\n");//不能删除,否则会出错
		selection->querySubObject("Range")->querySubObject("Font")->setProperty("Size", size);//设置字体大小:小四12
		selection->querySubObject("Range")->querySubObject("Font")->setProperty("Name", FontName);//字体(在插入字符前设置字体)

		if (iscenter == 1)
			pBookmark->querySubObject("Range")->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");//水平居中
		pBookmark->querySubObject("Range")->querySubObject("ParagraphFormat")->setProperty("LineSpacingRule", "wdLineSpace1pt5");//1.5行距  
		pBookmark->querySubObject("Range")->querySubObject("ParagraphFormat")->setProperty("LineUnitAfter", 0.5);//段后0.5
		pBookmark->querySubObject("Range")->setProperty("Text", sText);//插入字符
		delete pBookmark;
		//selection->querySubObject("Range")->querySubObject("Font")->setProperty("Bold", 1);//加粗
	}
	return true;
}
/*****删除标签处文本
******input:(QString)标签名
******output:
*/
bool WordEngine::deleteLable(QString sLabel)
{
	if (!m_pWorkDocument) {
		return false;
	}
	//获取文档中名字为sLabel的标签
	QAxObject *pBookmark = m_pWorkDocument->querySubObject("Bookmarks(QString)", sLabel);
	if (pBookmark)
	{
		pBookmark->dynamicCall("Select(void)");
		pBookmark->querySubObject("Range")->deleteLater();
		delete pBookmark;
	}
	return true;
}
/*****标签处添加图片
******input:(QString)标签名字,(QString)图片地址
******output: (bool) 
*/
bool WordEngine::replacePic(QString sLabel, QString sFile)
{
	if (!m_pWorkDocument)
		return false;

	QAxObject *bookmark_pic = m_pWorkDocument->querySubObject("Bookmarks(QString)", sLabel);
	if (bookmark_pic)
	{
		bookmark_pic->dynamicCall("Select(void)");
		QAxObject *range = bookmark_pic->querySubObject("Range");
		QVariant tmp = range->asVariant();
		QList<QVariant> qList;
		qList << QVariant(sFile);
		qList << QVariant(false);
		qList << QVariant(true);
		qList << tmp;
		QAxObject *Inlineshapes = m_pWorkDocument->querySubObject("InlineShapes");
		Inlineshapes->dynamicCall("AddPicture(const QString&,QVariant,QVariant,QVariant)", qList);
		delete Inlineshapes;
	}
	return true;
}
/*****标签处插入表格:不带头
******input:(QString)标签名字,(int)表格行数,(int)列数
******output: (QAxObject)
*/
QAxObject *WordEngine::insertTable(QString sLabel, int row, int column)
{
	QAxObject *bookmark = m_pWorkDocument->querySubObject("Bookmarks(QVariant)", sLabel);
	if (bookmark)
	{
		bookmark->dynamicCall("Select(void)");
		QAxObject *selection = m_pWord->querySubObject("Selection");

		selection->dynamicCall("InsertAfter(QString&)", "\n");
		//selection->dynamicCall("MoveLeft(int)", 1);
		selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphCenter");//水平居中
		//selection->querySubObject("Cells")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
		//selection->dynamicCall("TypeText(QString&)", "Table Test");//设置标题

		QAxObject *range = selection->querySubObject("Range");
		QAxObject *tables = m_pWorkDocument->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.toLatin1().constData());
			borders->dynamicCall("SetLineStyle(int)", 1);
		}
		return table;
	}
	return NULL;
}
/*****标签处插入表格:带头
******input:(QString)标签名字,(int)表格行数,(int)列数,(QStringList)表头数据
******output: (QAxObject)
*/
QAxObject *WordEngine::insertTable(QString sLabel, int row, int column, QStringList headList)
{
	QAxObject *bookmark = m_pWorkDocument->querySubObject("Bookmarks(QVariant)", sLabel);
	if (headList.size() != column) {
		return NULL;
	}
	if (bookmark)
	{
		bookmark->dynamicCall("Select(void)");
		QAxObject *selection = m_pWord->querySubObject("Selection");

		selection->dynamicCall("InsertAfter(QString&)", "\r\n");
		//selection->dynamicCall("MoveLeft(int)", 1);
		selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphCenter");//水平居中
		//selection->querySubObject("Cells")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
		//设置标题
		//selection->dynamicCall("TypeText(QString&)", "Table Test");

		QAxObject *range = selection->querySubObject("Range");
		QAxObject *tables = m_pWorkDocument->querySubObject("Tables");
		QAxObject *table = tables->querySubObject("Add(QVariant,int,int)", range->asVariant(), row, column);
		//表格自动拉伸列 0固定  1根据内容调整  2 根据窗口调整
		table->dynamicCall("AutoFitBehavior(WdAutoFitBehavior)", 2);

		//设置表头
		for (int i = 0; i < headList.size(); i++) {
			table->querySubObject("Cell(int,int)", 1, i + 1)->querySubObject("Range")->dynamicCall("SetText(QString)", headList.at(i));
			//加粗
			table->querySubObject("Cell(int,int)", 1, i + 1)->querySubObject("Range")->dynamicCall("SetBold(int)", true);
		}

		for (int i = 1; i <= 6; i++)
		{
			QString str = QString("Borders(-%1)").arg(i);
			QAxObject *borders = table->querySubObject(str.toLatin1().constData());
			borders->dynamicCall("SetLineStyle(int)", 1);
		}
		return table;
	}
	return NULL;
}
/*****为表格添加行
******input:(QAxObject)表格指针,(int)第几行处添加,(int)共添加几行
******output:
*/
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 (size_t 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);
		}
	}
}
/*****获取表格行数
******input:所选信号
******output: (int)
*/
int WordEngine::currenRow()
{
	QAxObject*selection = m_pWord->querySubObject("Selection");
	int row = selection->dynamicCall("Information(QVariant&)", 10).toInt();
	return row;
}
/*****合并单元格
******input:(int)开始行,(int)开始列,(int)结束行,(int)结束列,(QAxObject)表格指针
******output: (QAxObject)
*/
void WordEngine::MergeCells(int nStartRow, int nStartCol, int nEndRow, int nEndCol, QAxObject *table, int tableIndex)
{
	if (nullptr == table)
	{
		return;
	}
	if (table)
	{
		QAxObject* StartCell = table->querySubObject("Cell(int, int)", nStartRow, nStartCol);
		QAxObject* EndCell = table->querySubObject("Cell(int, int)", nEndRow, nEndCol);
		if (nullptr == StartCell)
		{
			return;
		}
		if (nullptr == EndCell)
		{
			return;
		}
		StartCell->querySubObject("Merge(QAxObject *)", EndCell->asVariant());
	}
}
/*****获取单元格内容 此处对于Excel来说列和行从1开始最少
******input:(int)行,(int)列
******output: (QVariant)
*/
QVariant WordEngine::getCellValue(int row, int column)					
{
	QAxObject* selection = m_pWord->querySubObject("Selection");
	QAxObject* table = selection->querySubObject("Tables(1)");
	if (nullptr != selection && nullptr != table)
		return table->querySubObject("Cell(int, int)", row, column)->querySubObject("Range")->property("Text");
	else
		return QVariant("");
}
/*****获取单元格内容 此处对于Excel来说列和行从1开始最少
******input:(int)行,(int)列,(QAxObject)表格指针
******output: (QVariant)
*/
QVariant WordEngine::getCellValue(int row, int column, QAxObject *table)				
{
	if (nullptr != table)
	{
		QAxObject *cell = table->querySubObject("Cell(int, int)", row, column);
		if (cell)
			return cell->querySubObject("Range")->property("Text");
	}
	return QVariant("");
}
/*****设置表格列宽
******input:(QAxObject)表格指针,(int)列,(int)宽度
******output: 
*/
void WordEngine::setColumnWidth(QAxObject *table, int column, int width)
{
	if (!table) {
		return;
	}
	table->querySubObject("Columns(int)", column)->setProperty("Width", width);
}
/*****设置表格内容
******input:(QAxObject)表格指针,(int)行,(int)列,(int)内容
******output: 
*/
void WordEngine::SetTableCellString(QAxObject *table, int row, int column, QString text,int Alignment)
{
	if (!table)
		return;
	QAxObject *cell = table->querySubObject("Cell(int,int)", row, column);
	if (!cell)
		return;
	cell->dynamicCall("Select(void)");
	if (!cell)
		return;
	cell->querySubObject("Range")->setProperty("Text", text);
	if (row == 1)		//加粗
		cell->querySubObject("Range")->dynamicCall("SetBold(int)", true);
	setAlignment(Alignment);
	cell->querySubObject("Range")->querySubObject("Font")->setProperty("Size", 10);
	cell->querySubObject("Range")->querySubObject("Font")->setProperty("Name", "Times New Roman");
}

void WordEngine::saveLastError(int arg1, QString arg2, QString arg3, QString arg4)
{
	qDebug() << "QAxBase Error:" << QString::number(arg1) << arg2 << arg3 << arg4;
}

void WordEngine::setRowAlignment(QAxObject *table, int row, int flag)
{
	if (nullptr == table)
	{
		return;
	}
	QAxObject* Row = table->querySubObject("Rows(int)", row);
	if (nullptr == Row)
	{
		return;
	}
	QAxObject* range = Row->querySubObject("Range");
	if (nullptr == range)
	{
		return;
	}
	Row->querySubObject("Alignment(int)", flag);
	if (flag == 0)
	{
		range->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");//水平居中
		range->querySubObject("Cells")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
	}
	else if (flag == 1)
	{
		range->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphJustify");
		range->querySubObject("Cells")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
	}
	else if (flag == 2)//wdAlignParagraphJustifyMed
	{
		range->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphRight");
		range->querySubObject("Cells")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
	}
	else if (flag == 3)
	{
		range->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphLeft");
		range->querySubObject("ParagraphFormat")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
	}
}

void WordEngine::setCellAlignment(QAxObject *table, int row, int col, int flag)
{
	if (nullptr == table)
	{
		return;
	}
	QAxObject *cell = table->querySubObject("Cell(int,int)", row, col);
	if (nullptr == cell)
	{
		return;
	}
	QAxObject* range = cell->querySubObject("Range");
	if (nullptr == range)
	{
		return;
	}
	cell->querySubObject("Alignment(int)", flag);
	if (flag == 0)
	{
		range->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");//水平居中
		range->querySubObject("Cells")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
	}
	else if (flag == 1)
	{
		range->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphJustify");
		range->querySubObject("Cells")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
	}
	else if (flag == 2)//wdAlignParagraphJustifyMed
	{
		range->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphRight");
		range->querySubObject("Cells")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
	}
	else if (flag == 3)
	{
		range->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphLeft");
		range->querySubObject("ParagraphFormat")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");//垂直居中
	}
}

文章来源地址https://www.toymoban.com/news/detail-653301.html

到了这里,关于QT技术实现Word模板编辑及转PDF的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • java word转pdf,word模板

    maven poi-tl语法参考文档 http://deepoove.com/poi-tl/ 测试poi-tl 测试word转pdf test.docx 截图 template.docx截图 效果截图

    2024年02月06日
    浏览(37)
  • Word模板替换,并转PDF格式输出

    Poi-tl参考文档地址:http://deepoove.com/poi-tl/1.8.x/#hack-loop-table         绿色部分是直接渲染的,对应map中的key-value,蓝色部分是绑定collections对象,进行遍历循环集合数据         转换的pdf有水印,去水印很方便, 加载License(要买)即可 封装一个工具类 https://blog.csdn.net

    2024年02月11日
    浏览(31)
  • Java根据word模板生成word文档并转成PDF文件

    定义完我们的模板之后,我们要将文档保存为xml的格式 生成的xml格式看起来比较乱,没有层次感, 所以需要格式化一下 格式化 基础信息的定义 基础信息的定义只要保证我们转化成的xml文件中的${name}等格式没错误即可 表格的定义 遍历实现,表格的数据填充 在xml文件中我们的

    2024年02月09日
    浏览(49)
  • java按照模板导出pdf或者word

    (一)制作模板  1、在word里制作模板         因为PDF常用的软件不支持编辑,所以先用Word工具,如WPS或者Office新建一个空白Word文档,里面制作出自己想要的样式。 2、 将Word转换成PDF形式          将设置好的Word文档转换成PDF形式,保存起来。 3、编辑PDF准备表单 

    2024年02月06日
    浏览(43)
  • aspose 使用ftl模板生成word和pdf

    1 先找到word模板,用${},替换变量,保存,然后另存为xml,最后把xml后缀改成ftl。 如下图: word 模板文件 ftl模板文件如下: 2 代码生成 下面函数将ftl填充数据,并生成word和pdf 3 测试主程序 4 结果: pdf文件 word文件 还可以生成图片:

    2024年02月13日
    浏览(32)
  • Java使用ftl模板文件生成Word,以及Word转换图片或Pdf工具类

    一、写在前面 最近在项目中使用打印功能,发现这个功能我已经写过多次了,下面这个文章的发步日期在2020年,不得不感慨时间之快啊。 https://blog.csdn.net/weixin_43238452/article/details/109636200?spm=1001.2014.3001.5501 下面介绍一下应用场景:这次项目依旧是springboot项目,使用ftl模版生

    2024年02月15日
    浏览(48)
  • QT生成Word PDF文档

    需求:将软件处理的结果保存为一个报告文档,文档中包含表格、图片、文字,格式为word的.doc和.pdf。生成word是为了便于用户编辑。 开发环境:qt4.8.4+vs2010 在qt的官网上对于pdf的操作介绍如下:http://qt-project.org/wiki/Handling_PDF 。即通过QPrinter类来创建pdf;还有通过第三方库Po

    2024年02月13日
    浏览(46)
  • JAVA之利用easypoi将word模板导出为pdf(可带图片)

    EasyPoi是一款基于POI的Java快速导出/导入Excel工具。它在POI的基础上进行了封装,提供了更加简洁易用的API,使得生成Excel文件更加容易和高效。 使用EasyPoi可以轻松地生成Excel文件,并支持多种格式,如xlsx、xls、csv等。同时,EasyPoi也支持读取Excel文件,可以方便地获取其中的数

    2024年02月08日
    浏览(45)
  • (Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出

    目录 1、引入jar包 2、pdf处理工具类 3、poi模板导出工具类 4、测试类 5、模板 6、最终效果  1、引入jar包   2、pdf处理工具类  3、poi模板导出工具类  4、测试类 5、模板 6、最终效果 

    2024年02月06日
    浏览(65)
  • 使用 Qt 生成 Word 和 PDF 文档的详细教程

    前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。 Qt 是一个跨平台的应用程序开发框架,除了用于创建图形界面应用程序外,还可以用来生成 Word 和 PDF 文档。本文

    2024年02月12日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包