转载自:以前在网络上查的资料,很长时间了,忘记出处了,望原作者谅解!下面是我根据需要整理的。
// m_strFilePath 是文件绝对路径(不包含文件名),貌似相对路径不能用!
QString strFilePathName = m_strFilePath + "/temp.xlsx";
QAxObject excel("Excel.Application");
excel.setProperty("Visible", false);
QAxObject* work_books = excel.querySubObject("WorkBooks");
QAxObject* workbooks = excel.querySubObject("WorkBooks");
workbooks->dynamicCall("Open(const QString&)", strFilePathName);
QAxObject* workbook = excel.querySubObject("ActiveWorkBook");
QAxObject* sheets = workbook->querySubObject("Sheets");
QAxObject* sheet = workbook->querySubObject("Sheets(int)", 1);
QAxObject* range = sheet->querySubObject("UsedRange");
QAxObject* rows = range->querySubObject("Rows");
QAxObject* columns = range->querySubObject("Columns");
// 注意行、列中多余的(如:列标题)数据的排除
int rowStart = range->property( "Row" ).toInt();
int columnStart = range->property( "Column" ).toInt();
int nRow = rows->property( "Count" ).toInt();
int nColumn = columns->property( "Count" ).toInt();
for ( i=rowStart; i<=nRow; i++ )
{
for ( int m=columnStart; m<nColumn; m++ )
{
QAxObject* cell = range->querySubObject( "Cells(int,int)", i, m );
QString strValue = cell->property( "Value" ).toString();
if ( strValue != "" )
{
qDebug() << strValue << endl;
}
}
}
workbook->dynamicCall( "Close(Boolen)", false); // 关闭文件
excel.dynamicCall( "Quit(void)" ); // 退出
terminateExcel(); // 结束 Excel 进程,否则系统会很卡顿!!!
注意:不知什么原因,Qt操作 Excel 文件后,会产生很多 Excel 进程,需要手动结束该进程
terminateExcel() 函数的具体定义,请参考:http://blog.csdn.net/cao269631539/article/details/60479616