簡體   English   中英

如何使用C#和ADO.NET從Excel中讀取小數和日期

[英]How to read decimal and dates from Excel with C# and ADO.NET

我正在嘗試使用以下代碼(ADO.NET)在ASP.NET應用程序中讀取Excel文件:

// Create OleDbCommand object and select data from worksheet Sheet1    
String query = String.Format("Select * From [{0}$]", sheetName);
OleDbCommand cmd = new OleDbCommand(query, oledbConn);

// Create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;

//Fills Data to DataTable
oleda.Fill(dt);

問題在於數據表中的值被表示

1)對於帶逗號(3,14)或帶點(3.14)的小數

2)對於格式為“ DD / MM / YYYY”或“ MM / DD / YYYY”的日期

對於相同的Excel文件,取決於服務器的語言環境設置。

有什么方法可以讀取特定語言環境中的數據,以便從Excel文件中獲取正確的值?

對於帶有小數的列,請使用以下內容對其進行解析:( Decimal.Parse

string decimal1 = "3,14";
string decimal2 = "3.14";

decimal d1 = decimal.Parse(decimal1, new NumberFormatInfo { NumberDecimalSeparator = "," });
decimal d2 = decimal.Parse(decimal2);

請注意,使用,您需要使用自定義NumberFormatInfo對其進行正確解析。

然后為您的DateTime列:

string date1 = "14/03/2018";
string date2 = "03/14/2018";

DateTime dt1 = DateTime.ParseExact(date1, "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.ParseExact(date2, "MM/dd/yyyy", CultureInfo.InvariantCulture);

在這里,您將要指定日期的不同格式。


編輯:

為了更全面地解析未知的DateTime格式,如果您知道可能有多個,可以嘗試遍歷CultureInfo或多種CultureInfo所有格式。 以下是如何執行此操作的示例:

string dateTimeString = @"03/14/2018";

string[] possibleStandardFormats = new CultureInfo("en-US")
                                     .DateTimeFormat.GetAllDateTimePatterns();

DateTime? result = null;
foreach (string format in possibleStandardFormats) {
    if (DateTime.TryParse(dateTimeString, out DateTime dateTime)) {
        // this format could work
        result = dateTime;
        break;
    }
}

if (result == null) {
    // no luck with any format
    // try one last parse
    if (DateTime.TryParse(dateTimeString, out DateTime dateTime)) {
        // finally worked
        result = dateTime;
    }
    else {
        // no luck
    }
}

在這里,首先嘗試常規的DateTime.TryParse可能更有效(如本示例結尾所示),因為它可以為您節省其他格式的迭代。 由您決定如何處理,但是此示例應處理大多數情況。

編輯2:

為了獲得標准的DateTime格式,您可以使用CurrentCulture ,它將對您的日期有所幫助。 在我之前的編輯中,我對new CultureInfo("en-US")硬編碼,但以下內容更為通用。

string[] possibleStandardFormats = new CultureInfo(CultureInfo.CurrentCulture.Name)
                                            .DateTimeFormat.GetAllDateTimePatterns();

編輯3:要進一步解釋小數點以前的解析,請首先檢查字符串是否有逗號,然后根據我上面列出的方法解析它。

string decimal1 = "3,14";

if (decimal1.Contains(",")) {
    decimal d1 = decimal.Parse(decimal1, new NumberFormatInfo { NumberDecimalSeparator = "," });
}
else {
    decimal d1 = decimal.Parse(decimal1);
}

編輯4:

要將區域性納入解析小數,可以嘗試使用Convert.ToDecimal方法。 它的參數之一是CultureInfo ,您可以在其中將當前文化作為CultureInfo.CurrentCulture傳遞。 例如,在下面的示例中,我使用的是de-de (德語),因為這是1.234,14的有效區域性

string decimal1 = "1.234,14";
string decimal2 = "1,234.14";

decimal d1 = Convert.ToDecimal(decimal1, new CultureInfo("de-de"));
decimal d2 = Convert.ToDecimal(decimal2, CultureInfo.CurrentCulture);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM