qt windows 導入導出xls

說明:從qtableview導入導出excel和csv文件,excel包括xls和xlsx文件,需要包含頭文件和lib庫

#include <ActiveQt\QAxObject>

Qt5AxContainerd.lib
Qt5AxServerd.lib
Qt5AxBased.lib

1、導入excel

void qexceldemo::ImportExcel(QString fileName)
{
QAxObject *excel = NULL;
QAxObject *workbooks = NULL;
QAxObject *workbook = NULL;
QAxObject *cell=NULL;


excel = new QAxObject("Excel.Application");
if (excel->isNull()) 
{
if (excel != NULL)//網絡中很多使用excel==NULL判斷,是錯誤的
{
excel->dynamicCall("Quit (void)");
delete excel;
}


QMessageBox::critical(0, "Import", "not find EXCEL!");
return;
}
excel->dynamicCall("SetVisible(bool)", false);
workbooks = excel->querySubObject("WorkBooks");
workbook = workbooks->querySubObject("Open(QString,QVariant,QVariant)", fileName,3,true);//兩個參數時,三個參數true和false都很正常,false 鎖定excel文件,其它程序只能只讀方式打開,否則程序正在處理excel文件時,在外面打開excel,程序異常退出
if (!workbook) 
{
if (excel != NULL)
{
excel->dynamicCall("Quit (void)");
delete excel;
}
QMessageBox::critical(0, "Import", "excel is not exist!");
return;
}
QAxObject * worksheet = workbook->querySubObject("WorkSheets(int)", 1);//打開第一個sheet
QAxObject * usedrange = worksheet->querySubObject("UsedRange");//獲取該sheet的使用範圍對象
QAxObject * rows = usedrange->querySubObject("Rows");
QAxObject * columns = usedrange->querySubObject("Columns");


int intRowStart = usedrange->property("Row").toInt();
int intColStart = usedrange->property("Column").toInt();
int intCols = columns->property("Count").toInt();
int intRows = rows->property("Count").toInt();
QString str;


ui.tableWidgetExcel->setRowCount(intRows);
ui.tableWidgetExcel->setColumnCount(intCols);


for(int i=intRowStart;i <intRowStart + intRows;i++)
{
for(int j=intColStart ;j<intColStart+intCols;j++)
{
cell = worksheet->querySubObject("Cells(int,int)", i,j ); //獲取單元格
str = cell->property("Value").toString();
if(cell->property("Value").type()==QVariant::Double)
{
qDebug()<<QString::number(cell->property("Value").toDouble(),'f',0);
}
else if(cell->property("Value").type()==QVariant::String)
{
qDebug()<<str;
}
QTableWidgetItem *item = new QTableWidgetItem(str);
ui.tableWidgetExcel->setItem(i - intRowStart, j - intColStart, item);
}
}
workbook->dynamicCall("Close (Boolean)", false);
excel->dynamicCall("Quit (void)");
delete workbook;
delete workbooks;
delete excel;
}

2、導出excel

void qexceldemo::ExportExcel(QString fileName)
{
QAxObject *excel = new QAxObject("Excel.Application");
if (excel->isNull()) 
{
if (excel != NULL)//網絡中很多使用excel==NULL判斷,是錯誤的
{
excel->dynamicCall("Quit()");
delete excel;
}
QMessageBox::critical(0, "錯誤信息", "沒有找到EXCEL應用程序");
return;
}
QAxObject *workbooks = NULL;
QAxObject *workbook = NULL;
QAxObject *worksheets = NULL;
QAxObject *worksheet = NULL;


excel->dynamicCall("SetVisible (bool)", false);//不顯示窗體
excel->setProperty("DisplayAlerts", false);//不顯示任何警告信息。如果爲true那麼在關閉是會出現類似“文件已修改,是否保存”的提示
workbooks = excel->querySubObject("WorkBooks");//獲取工作簿集合


if (QFile::exists(fileName))
{
workbook = workbooks->querySubObject("Open(const QString &)", fileName);
}
else
{
workbooks->dynamicCall("Add");//新建一個工作簿
workbook = excel->querySubObject("ActiveWorkBook");//獲取當前工作簿
}


worksheets = workbook->querySubObject("Sheets");//獲取工作表集合
worksheet = worksheets->querySubObject("Item(int)",1);//獲取工作表集合的工作表1,即sheet1


//刪除工作表(刪除第一個)
//QAxObject *first_sheet = worksheets->querySubObject("Item(int)", 1);
//first_sheet->dynamicCall("delete");


////插入工作表(插入至最後一行)
//QAxObject *last_sheet = worksheets->querySubObject("Item(int)", 1);
//worksheet = worksheets->querySubObject("Add(QVariant)", last_sheet->asVariant());
//last_sheet->dynamicCall("Move(QVariant)", worksheet->asVariant());
//worksheet->setProperty("Name", "Sheet1");  //設置工作表名稱


QAxObject * usedrange = worksheet->querySubObject("UsedRange");//獲取該sheet的使用範圍對象
QAxObject * rows = usedrange->querySubObject("Rows");
QAxObject * columns = usedrange->querySubObject("Columns");
int intRowStart = usedrange->property("Row").toInt();
int intColStart = usedrange->property("Column").toInt();
int intCols = columns->property("Count").toInt();
int intRows = rows->property("Count").toInt();


QAxObject *cell = NULL;
QString str;
int rowCount = ui.tableWidgetExcel->rowCount();
int colCount = ui.tableWidgetExcel->columnCount();


// 清空數據
for(int i=intRowStart;i <intRowStart + intRows;i++)
{
for(int j=intColStart ;j<intColStart+intCols;j++)
{
cell = worksheet->querySubObject("Cells(int,int)", i,j ); //獲取單元格
cell->setProperty("Value", "");
}
}


// 插入數據
for (int i = intRowStart; i < intRowStart + rowCount; i++)
{
for(int j = intColStart; j < intColStart + colCount; j++)
{
str = ui.tableWidgetExcel->item(i - intRowStart, j - intColStart)->text();
cell = worksheet->querySubObject("Cells(int,int)", i, j);//獲取單元格
cell->setProperty("Value", str);
}
}


workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(fileName));//保存至filepath,注意一定要用QDir::toNativeSeparators將路徑中的"/"轉換爲"\",不然一定保存不了。
workbook->dynamicCall("Close()");//關閉工作簿
excel->dynamicCall("Quit()");//關閉excel
delete workbook;
delete workbooks;
delete excel;
}

3、導入csv

void qexceldemo::ImportCsv(QString fileName)
{
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Open file failed!";
return;
}

QList<QStringList> qlist;
QStringList strlist;
QTextStream in(&file);
int row = 0;
int col = 0;


while(!in.atEnd())
{
QString fileLine = in.readLine();
strlist = fileLine.split(",", QString::SkipEmptyParts);
qlist.push_back(strlist);


// 取更小值
if (col == 0)
{
col = strlist.count();
}
else
{
col = col < strlist.count() ? col : strlist.count();
}
row++;
}
ui.tableWidgetExcel->setRowCount(row);
ui.tableWidgetExcel->setColumnCount(col);


for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
QTableWidgetItem *item = new QTableWidgetItem(qlist[i][j]);
ui.tableWidgetExcel->setItem(i, j, item);
}
}


file.close();
}

4、導出csv

void qexceldemo::ExportCsv(QString fileName)
{
//打開.csv文件
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
qDebug() << "Open file failed!";
return;
}


QTextStream out(&file);
QString str;


//獲取表格內容
int row = ui.tableWidgetExcel->rowCount();//表格總行數
int col = ui.tableWidgetExcel->columnCount();
for(int i = 0; i < row; i ++)
{
for(int j = 0; j < col; j++)
{
str = ui.tableWidgetExcel->item(i, j)->text();
out << str << ",";// 寫入文件
}
out << "\n";
}


file.close();
}

發佈了70 篇原創文章 · 獲贊 11 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章