简体   繁体   English

如何使用C#和ADO.NET从Excel中读取小数和日期

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

I am trying to read an Excel file in my ASP.NET application using the following piece of code (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);

The problem is that values in the data table are represented 问题在于数据表中的值被表示

1) For decimals either with a comma (3,14) or with a dot (3.14) 1)对于带逗号(3,14)或带点(3.14)的小数

2) For dates with either the format 'DD/MM/YYYY' or'MM/DD/YYYY' 2)对于格式为“ DD / MM / YYYY”或“ MM / DD / YYYY”的日期

For the same Excel file depending on the locale settings server has. 对于相同的Excel文件,取决于服务器的语言环境设置。

Is there any way to read the data in a specific locale in order to get the correct values from the Excel file? 有什么方法可以读取特定语言环境中的数据,以便从Excel文件中获取正确的值?

In the case of the column with decimals, use the following to parse them: ( Decimal.Parse ) 对于带有小数的列,请使用以下内容对其进行解析:( Decimal.Parse

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

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

Note that with a , you need to use a custom NumberFormatInfo for it to parse right. 请注意,使用,您需要使用自定义NumberFormatInfo对其进行正确解析。

Then for your DateTime column: 然后为您的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);

Here you will want to specify the differnt formats for your dates. 在这里,您将要指定日期的不同格式。


EDIT: 编辑:

To be more general about parsing an unknown DateTime format, you could try iterating through all the formats for your CultureInfo or multiple CultureInfo if you know there might be more than one. 为了更全面地解析未知的DateTime格式,如果您知道可能有多个,可以尝试遍历CultureInfo或多种CultureInfo所有格式。 An example is below of how you could do this: 以下是如何执行此操作的示例:

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
    }
}

Here it may be more effective to try the general DateTime.TryParse first (shown at the end of this example), as it could save you the iterations through the other formats. 在这里,首先尝试常规的DateTime.TryParse可能更有效(如本示例结尾所示),因为它可以为您节省其他格式的迭代。 Up to you how you want to handle this, but this example should handle the majority of the cases. 由您决定如何处理,但是此示例应处理大多数情况。

EDIT 2: 编辑2:

In order to get the standard DateTime formats, you can use the CurrentCulture which will help with your dates. 为了获得标准的DateTime格式,您可以使用CurrentCulture ,它将对您的日期有所帮助。 In my previous edit, I hard coded new CultureInfo("en-US") , but the below is a bit more general. 在我之前的编辑中,我对new CultureInfo("en-US")硬编码,但以下内容更为通用。

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

EDIT 3: To expound a bit more on the previous parsing of decimals, first check if the string has a comma and then parse it according to the method I have listed above. 编辑3:要进一步解释小数点以前的解析,请首先检查字符串是否有逗号,然后根据我上面列出的方法解析它。

string decimal1 = "3,14";

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

EDIT 4: 编辑4:

To incorporate culture into parsing decimals, you can try the Convert.ToDecimal method. 要将区域性纳入解析小数,可以尝试使用Convert.ToDecimal方法。 One of its parameters takes a CultureInfo where you can pass in your current culture as CultureInfo.CurrentCulture . 它的参数之一是CultureInfo ,您可以在其中将当前文化作为CultureInfo.CurrentCulture传递。 For example below, I am using de-de (German) since that is a valid culture for 1.234,14 例如,在下面的示例中,我使用的是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.

相关问题 如何将excel文件一列的所有内容读入数组C#? 不使用 ADO.net 方法 - How to read all contents of a column of excel file into an array C#? Without using ADO.net approach 如何使用C#ADO.NET更新Excel行? - How to update a excel row using C# ADO.NET? 如何在C#中使用ODBC读取特定Excel工作表中的所有数据行到ADO.NET数据表中 - How to read all data rows in a specific Excel sheet into an ADO.NET Datatable with out using ODBC in C# 什么是ADO.NET的替代方法,但在C#中以优雅的方式读取Excel文件 - What is an alternative to ADO.NET, but elegant way in C# to read Excel files 如何使用WPF C#和Ado.Net数据实体将十进制值插入货币数据类型列 - How to insert a decimal value to money data type column with wpf C# and Ado.Net Data Entity 在 C# 中通过 ADO.Net 导入 Excel - Excel import through ADO.Net in C# 使用ADO.Net在C#中读取Excel文件时出现问题 - Problem while reading excel file in C# with ADO.Net 使用 C# FormApp 和 ADO.NET 读取 db 文件 - Read a db file with C# FormApp and ADO.NET 有没有一种方法可以使用C#从ado.net查询中提取Excel文件并向其中添加自定义列 - Is there a way for extracting an Excel file from an ado.net query and adding custom columns to it using c# 使用C#从Excel到数据库ADO.net的导入数据中选择空格表 - select spacific sheet in import data from Excel to database ADO.net using C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM