1. 程式人生 > >QT檔案儲存--excel、txt

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;