C# ASP.NET 讀取EXCEL 儲存格 讀取 空值 不顯示

來源:互聯網
上載者:User

標籤:class   blog   http   tar   ext   com   

跟大家分享一下,【摘自】:http://blog.csdn.net/li185416672/article/details/8213729

讀取excel時,某些儲存格為空白值

原來如此:

當我們用olebb讀取excel的時候,如果沒有配置imex=1的屬性,微軟的處理機制是將列轉換為同一類型來讀取的.例如你在第一行寫的數字格式,而第二行寫的字元格式設定,就會出現某些列有值卻讀不出來.其實問題也很簡單,如果知道問題所在的話.屬性設定為"imex=1"即可

附以下參考:

string xlsdriver = @"provider=microsoft.jet.oledb.4.0;data source={0};extended properties=‘excel 8.0;imex=1‘;";
oledbconnection conn = new oledbconnection(string.format(xlsdriver, filename));

"hdr=yes;" indicates that the first row contains columnnames, not data.
"hdr=no;" indicates the opposite.
"imex=1;" tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. note that this option might affect excel sheet write access negative.
加上imex=1這個屬性,excel儲存格的值就會以文本型讀取,避免由於資料類型不一致導致某些值讀不出來的

找不到可安裝的ISAM

在進行將Excel匯入到應用程式時,提示“ 找不到可安裝的ISAM “的解決方案:

1.連接字串問

Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘  

(1)HDR表示要把第一行作為資料還是作為列名,作為資料用HDR=no,作為列名用HDR=yes;通過Imex=1來把混合型作為文本型讀取,避免 null值。

(2)左右兩個單引號不能少

 

2.只需註冊 Excel ISAM即可

在“運行”對話方塊中輸入斷行符號即可:Regsvr32 c:\WINDOWS\system32\msexcl40.dll

public DataSet ExcelReader(string excelName)
{
// 拼字連接字串,開啟串連
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + excelName + ";Extended Properties=‘Excel 8.0; HDR=YES; IMEX=1‘";
OleDbConnection objConn = new OleDbConnection(strConn);
objConn.Open();
// 取得Excel活頁簿中所有工作表
DataTable schemaTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
OleDbDataAdapter sqlada = new OleDbDataAdapter();
DataSet ds = new DataSet();
// 遍曆工作表取得資料並存入Dataset
foreach (DataRow dr in schemaTable.Rows)
{
try
{
string strSql = "Select * From [" + dr[2].ToString().Trim() + "]";
OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
sqlada.SelectCommand = objCmd;
sqlada.Fill(ds, dr[2].ToString().Trim());
}
catch (Exception ex)
{

}
}
objConn.Close();
return ds;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.