C#讀取Excel數(shù)據(jù)需要注意的三點
用OLEDB進(jìn)行C#讀取Excel數(shù)據(jù),并返回DataSet數(shù)據(jù)集。其中有幾點需要注意的:
C#讀取Excel數(shù)據(jù)1.連接字符串中參數(shù)IMEX 的值:
- 0 is Export mode 1 is Import mode
- 2 is Linked mode (full update capabilities)
IMEX有3個值:當(dāng)IMEX=2 時,EXCEL文檔中同時含有字符型和數(shù)字型時,比如第C列有3個值,2個為數(shù)值型 123,1個為字符型 ABC,當(dāng)導(dǎo)入時,頁面不報錯了,但庫里只顯示數(shù)值型的123,而字符型的ABC則呈現(xiàn)為空值。當(dāng)IMEX=1時,無上述情況發(fā)生,庫里可正確呈現(xiàn) 123 和 ABC.
C#讀取Excel數(shù)據(jù)2.參數(shù)HDR的值:
HDR=Yes,這代表***行是標(biāo)題,不做為數(shù)據(jù)使用 ,如果用HDR=NO,則表示***行不是標(biāo)題,做為數(shù)據(jù)來使用。系統(tǒng)默認(rèn)的是YES
C#讀取Excel數(shù)據(jù)3.參數(shù)Excel 8.0
對于Excel 97以上版本都用Excel 8.0Google AdSense 會在您的網(wǎng)站上提供與內(nèi)容相關(guān)的廣告
- /**//// 〈 summary〉
- /// 讀取Excel文件,將內(nèi)容存儲在DataSet中
- /// 〈 /summary〉
- /// 〈 param name="opnFileName"〉
- 帶路徑的Excel文件名〈 /param〉
- /// 〈 returns〉 DataSet〈 /returns〉
- private DataSet ExcelToDataSet
- (string opnFileName)
- ...{
- string strConn = "Provider=Microsoft.
- Jet.OLEDB.4.0;Data Source=
- "+opnFileName+";
- Extended Properties=
- \"Excel 8.0;HDR=YES;IMEX=1\"";
- OleDbConnection conn =
- new OleDbConnection(strConn);
- string strExcel = "";
- OleDbDataAdapter myCommand = null;
- DataSet ds = new DataSet();
- strExcel = "select * from [sheet1$]";
- try
- ...{
- conn.Open();
- myCommand = new OleDbDataAdapter
- (strExcel, strConn);
- myCommand.Fill(ds,"dtSource");
- return ds;
- }
- catch (Exception ex)
- ...{
- MessageBox.Show("導(dǎo)入出錯:"
- + ex, "錯誤信息");
- return ds;
- }
- finally
- ...{
- conn.Close();
- conn.Dispose();
- }
- }
【編輯推薦】