QT讀取Excel 簡單範例程式碼
#include <QtGui>
#include <QAxObject>
#include <QAxWidget>
#include <qaxselect.h>
int main(int argc, char **argv)
{
QApplication a(argc, argv);
// QAxSelect select;
// select.show();
QAxWidget excel("Excel.Application");
excel.setProperty("Visible", true);//顯示當前視窗
//excel.setProperty("Caption","Invoke Microsoft Excel");//更改標題欄
QAxObject * workbooks = excel.querySubObject("WorkBooks");//獲取excel的集合指標
QAxObject *workbook = workbooks->querySubObject("Open (const QString &)",QString("c:/test.xls"));//開啟指定路徑的xls文件
QAxObject * worksheets = workbook->querySubObject("WorkSheets");//獲取sheets的集合指標
int intCount = worksheets->property("Count").toInt();//獲取sheets的數量
for (int i = 1; i <= intCount; i++)
{
int intVal;
QAxObject * worksheet = workbook->querySubObject("Worksheets(int)", i);//獲取指定位置的sheet頁面
qDebug() << i << worksheet->property("Name").toString();
QAxObject * range = worksheet->querySubObject("Cells(1,1)");//獲取sheet頁面中的C(1,1)資料
intVal = range->property("Value").toInt();//儲存該資料
range->setProperty("Value", QVariant(intVal+1));//將資料加1並重新儲存回C(1,1)
QAxObject * range2 = worksheet->querySubObject("Range(C1)");//???????????
intVal = range2->property("Value").toInt();
range2->setProperty("Value", QVariant(intVal+1));
}
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();
qDebug() << intRowStart;
int intColStart = usedrange->property("Column").toInt();
qDebug() << intColStart;
int intCols = columns->property("Count").toInt();
int intRows = rows->property("Count").toInt();
for (int i = intRowStart; i < intRowStart + intRows; i++)
{
for (int j = intColStart; j < intColStart + intCols; j++)
{
QAxObject * range = worksheet->querySubObject("Cells(int,int)", i, j );
qDebug() << i << j << range->property("Value");
}
}
excel.setProperty("DisplayAlerts", 0);
workbook->dynamicCall("SaveAs (const QString&)", QString("c:/xlsbyqt.xls"));
excel.setProperty("DisplayAlerts", 1);
workbook->dynamicCall("Close (Boolean)", false);
excel.dynamicCall("Quit (void)");
return a.exec();
}