我按照下载的例子做了一个读取Excel数据的程序。Excel:
钣金名称 a1 b1 c1 d1 e1 a2 b2 c2 d2 e2
bj001 h800 h800 600 600 r1000 800 800 600 600 1000
bj002 400 400 300 300 500 400 400 300 300 500 程序执行后,第二列的数据读取出现奇怪的问题。程序代码如下:
#include "excel9.h"
struct list * CTestExcelDlg::readExcel_worksheet(CString sFile, CString sheetname)
{
CStringArray * excel_row;
struct list * head;
head = NULL;
CDatabase   database; 
CStringArray * valid_fields =  new CStringArray();
//CStringArray * store_fields =  new CStringArray();
CString   sSql;   
CString   tmpItem;
CString urlparams;
CString   sDriver="Microsoft Excel Driver (*.xls)";   
CString   sDsn;   
//                                                                  
sDsn.Format("ODBC;DRIVER=%s;DSN="";DBQ=%s",   sDriver,   sFile); 
  try{             //   打开数据库(既Excel文件)
database.Open(NULL,   false,   false,  sDsn );    CRecordset   recset(&database);    //   设置读取的查询语句.   
sSql   =   "SELECT *  FROM  ["+sheetname+"$] ";    //   执行查询语句   
recset.Open(CRecordset::forwardOnly,   sSql,   CRecordset::readOnly);    //   获取查询结果    CODBCFieldInfo  mfi;
int nf= recset.GetODBCFieldCount();
CString nfs;
nfs.Format("%d",nf);
//AfxMessageBox(nfs);
CString hdr=""; for(int i=0;i<nf;i++)
{
recset.GetODBCFieldInfo(i,mfi);
// AfxMessageBox(mfi.m_strName);
hdr+=mfi.m_strName+",";
CString matched_field="";
valid_fields->Add(mfi.m_strName);

}
while   (!recset.IsEOF())   
{  
excel_row = new CStringArray();
CString msg_fcnt; for(int v=0;v<=valid_fields->GetUpperBound();v++)
{
//AfxMessageBox("valid_field :"+valid_fields->GetAt(v));
recset.GetFieldValue(valid_fields->GetAt(v),   tmpItem);  
这里在v=1,v=2的时候读出来的值为空。但是
                                              在把Excel中的"h800"改成“800”后,又能读出"800"。在新建表格时有时候能正确读取,但是对表格编辑后读取又出问题了,百思不得其解。请各位帮忙看看,谢谢了。
                                             excel_row->Add(tmpItem);
if(tmpItem != "")
{
excel_row->Add(tmpItem);
}
}
head = AddToList(excel_row,head);
 //   移到右一行   
  recset.MoveNext();   
}    //   关闭数据库   
database.Close();    }catch(...)
  {
delete valid_fields;
valid_fields=NULL;
return head;
  } delete valid_fields;
valid_fields=NULL;
}