專案需直接讀取 Excel 檔案資料,網路搜尋多為 ODBC 或 OLE 方式,兩者皆有侷限性。無奈之下,只能選擇最艱難的路徑——深入分析 Excel 二進位檔案格式(BIFF)。
Excel 採用 BIFF (Binary Interchange File Format) 格式,檔案由多筆「記錄」組成。每筆記錄包含:
Byte | 0 1 2 3 | 0 1 2 3 |
---------------------------
| 09 00 04 00 | 02 00 10 00 |
---------------------------
| opcode | length | version | file type |
09h 代表 BOF04h 記錄體 4 bytes02h 版本號10h 試算表檔案CFile f;
CFileException e;
if (!f.Open("D:\\Book1.xls", CFile::modeRead, &e)) {
TCHAR szError[1024];
e.GetErrorMessage(szError, 1024);
AfxMessageBox(szError);
return;
}
while (dwPos < dwLen) {
nRead = f.Read((void*)&RecNo, 2);
if (RecNo == XL_BOF) {
WORD Ver, Type;
f.Read((void*)&RecLen, 2);
f.Read((void*)&Ver, 2);
f.Read((void*)&Type, 2);
f.Seek(RecLen, CFile::current);
// 判斷版本與檔案類型...
break;
}
dwPos = f.GetPosition();
}
f.SeekToBegin();
dwPos = f.GetPosition();
while (dwPos < dwLen) {
nRead = f.Read((void*)&RecNo, 2);
switch (RecNo) {
case XL_BOUNDSHEET: // 工作表資訊
// 讀取工作表名稱...
break;
case XL_DIMENSION: // 儲存格範圍
f.Seek(RecLen, CFile::current);
break;
case XL_NUMBER: // 數值儲存格
break;
case XL_LABEL: // 字串儲存格
break;
case XL_EOF: // 檔案結尾
dwPos = dwLen;
break;
default:
f.Read((void*)&RecLen, 2);
f.Seek(RecLen, CFile::current);
break;
}
}
f.Close();
本文示範獨立於 MS Office 環境下,解析 BIFF 格式讀取 Excel 基本資訊。實際應用仍需更完整的記錄型別處理(筆者持續研究中)。讀取 Excel 方法不只一種,此為筆者採用之路徑,期盼與同好交流。
參考資料:Microsoft Excel File Format、MSDN Library