QT文件保存--excel、txt

对excel数据保存,一下为部分代码:

void savedatatoexcel(QString &fileName, QString &ss)
{
    newExcel(fileName);
    setCellValue(j - y + 1, i - x + 1, ss);
	saveExcel(fileName);
	freeExcel();	
}

void Thread::newExcel(const QString &fileName)
{
	HRESULT r = OleInitialize(0);
	CoInitialize(0);
	if (r != S_OK && r != S_FALSE) {
		qWarning("Qt: Could not initialize OLE (error %x)\n", (unsigned int)r);
	}
	pApplication = new QAxObject("Excel.Application");
	if (pApplication == NULL) {
		qWarning("pApplication\n"); return;
	}
	pApplication->dynamicCall("SetVisible(bool)", false);	//false不显示窗体
	pApplication->setProperty("DisplayAlerts", false);		//不显示任何警告信息。
	pWorkBooks = pApplication->querySubObject("Workbooks");
	QFile file(fileName);
	if (file.exists())
	{
		pWorkBook = pWorkBooks->querySubObject("Open(const QString &)", fileName);
	}
	else
	{
		pWorkBooks->dynamicCall("Add");
		pWorkBook = pApplication->querySubObject("ActiveWorkBook");
	}
	pSheets = pWorkBook->querySubObject("Sheets");
	pSheet = pSheets->querySubObject("Item(int)", 1);
}

void Thread::appendSheet(const QString &sheetName, int cnt)
{
	QAxObject *pLastSheet = pSheets->querySubObject("Item(int)", cnt);
	pSheets->querySubObject("Add(QVariant)", pLastSheet->asVariant());
	pSheet = pSheets->querySubObject("Item(int)", cnt);
	pLastSheet->dynamicCall("Move(QVariant)", pSheet->asVariant());
	pSheet->setProperty("Name", sheetName);
}

void Thread::setCellValue(int row, int column, const QString &value)
{
	QAxObject *pRange = pSheet->querySubObject("Cells(int,int)", row, column);
	pRange->dynamicCall("Value", value);
	QAxObject *interior = pRange->querySubObject("Interior");
	//设置单元格字体颜色
	interior->setProperty("Color", QColor(cl.r, cl.g, cl.b));
}

void Thread::saveExcel(const QString &fileName)
{
	pWorkBook->dynamicCall("SaveAs(const QString &)",
		QDir::toNativeSeparators(fileName));
}

void Thread::freeExcel()
{
	if (pApplication != NULL)
	{
		pApplication->dynamicCall("Quit()");
		delete pApplication;
		pApplication = NULL;
	}
	emit over();
}

对txt数据保存,一下为部分代码:

#include <iostream>
#include <QVector>
#include <string>
#include <fstream>
using namespace std;

void savetxt(QVector<double> vec,string sr)
{
	//将最终结果保存为xml或txt文档
	ofstream outfile;
	outfile.open(sr);
	for (int i = 0; i < vec.size(); i++)
	{
		outfile << vec[i] << endl;
	}
	outfile.close();
}

以及涉及一些文件名和系统时间命名规则,部分代码如下:

char Outname[200];
QDateTime dt;
QTime time;
QDate date;
dt.setTime(time.currentTime());
dt.setDate(date.currentDate());
QString qcurrentDate = dt.toString("yyyy.MM.dd.hh.mm.ss");
sprintf(Outname, "%s.xlsx", qcurrentDate.toLatin1().data());
QString vbvb = QString("%1").arg(Outname);
//其中前两个为参数,可随实际更改
QString fileNametmp = telecentricity1 + telecentricitypara1 + vbvb;

猜你喜欢

转载自blog.csdn.net/sc944201630/article/details/81280017
今日推荐