2012-08-09 35 views
2

我正在嘗試將Excel工作表數據讀取到數據表以綁定到GridView。我的Excel工作表包含以下數據:將Excel讀取到數據表而不會損失貨幣類型的精確度

ID Value1     Value2 
------------------------------------------------- 
1  $312976.97530297   $30790.0614862584 
etc 

我正在使用以下代碼將值讀取到數據表中。

DataTable table = new DataTable(); 
string filePath = @"D:\Book1.xlsx"; 
string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text\"", filePath); 
using (OleDbConnection dbConnection = new OleDbConnection(strConn)) 
{ 
using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT ID, value1,value2 FROM [Sheet1$]", dbConnection)) 
dbAdapter.Fill(table); 
} 

問題:由於value1和value2包含$符號,因此dataAdaptor將檢索兩個值而不是全部精度,即。而不是312976.97530297,僅返回312976.9753。

Note: 
1. I cannot change the input Excel sheet since the enduser will upload it to the web site. 
2. If i remove the $ symbol in the excel sheet, it will return the full precision, but $ also present in the input sheet. 
3. I tried using Microsoft.Office.Interop.Excel and its working, but the performance is very low. 


Or I can format all the excel cell as Text/General type before filling to the datatable, Anyone knows how to do that? 

請提出一個使用OleDbDataAdapter的方法。

在此先感謝, 威爾遜。

回答

0

@All,
最後我有一個複雜的方式:)做到了,
1格式化所有的Excel colums通用型使用互操作
2.閱讀Excel中一個DataTable使用oledbadaptor上傳後。 (現在我得到了全部的精度,因爲單元格類型是一般的)可編輯的
3.現在我將數據錶行類型轉換爲字符串,因爲我需要使用UDT將數據表值插入到SQL表中(不轉換我們也會在這裏損失精度)

無論如何,它現在的工作很好(一種替代方法總是歡迎e :)) Wilz ...

0

也許你應該給http://epplus.codeplex.com/releases/view/79802一試。它可以非常快速地讀取數據,至少與interop相比。另外,interop對於web服務來說不夠可靠。

對於您的問題:也許有逃脫的方法「$」

微軟建議使用雙或貨幣的情況下,浮動的數據類型。你使用什麼格式?

+0

基督徒,感謝您的答覆,我在C#中使用雙數據類型。它似乎沒有這個問題的適當的解決方案:( – Wilz 2012-08-10 05:01:19

+0

或者我可以格式化所有的Excel單元格爲文本/常規類型填充到數據表之前,任何人都知道如何做到這一點? – Wilz 2012-08-10 07:00:09