简体   繁体   English

如何将 excel.cell 的日期时间格式保存到数据集单元格中

[英]how to keep the datetimeformat of excel.cell into dataset cell

Having some hard time understanding the conversion between excel file to .net object type such as DataSet or DataTable.很难理解 excel 文件到 .net object 类型(如 DataSet 或 DataTable)之间的转换。

One issue I see in this 3rd party library (and the issue still lingers in the latest I believe) called ExcelDataReader is its conversion of datetime format.我在这个名为ExcelDataReader的第 3 方库中看到的一个问题(我相信这个问题仍然存在于最新版本中)是它对日期时间格式的转换。

For example the excel file where user set custom format of dd/mm/yyyy gets converted in the result of dataSet as mm/dd/yyyy after importing the excel file to the object done.例如 excel 文件,其中用户设置的自定义格式 dd/mm/yyyy 在将 excel 文件导入 ZA8CFDE6331BD4B662AC96F8911 后在 dataSet 的结果中转换为 mm/dd/yyyy

I was thinking maybe to fix this, the library code needs to passively receive the excel cell format settings, not trying to convert with its own settings.我在想也许可以解决这个问题,库代码需要被动接收 excel 单元格格式设置,而不是尝试使用自己的设置进行转换。

Wonder how in the code it can be done such that想知道如何在代码中做到这一点

if (excelfile.row[somenumber].cell.TypeSetting == typesetting.dateTime)
{ 
   dataset.cell[somenumber].dateTimeFormatSetting = excelfile.row[somenumber].cell.dateTimeFormatSetting
}

probably this code isn't close to be realistic, just a wild guess of what needs to be done.可能这段代码并不接近现实,只是对需要做什么的疯狂猜测。

ExcelDataReader loses Excel's formatting information when using AsDataSet() , which basically gives you only the raw values. ExcelDataReader 在使用AsDataSet()时会丢失 Excel 的格式信息,这基本上只为您提供原始值。

F.ex a raw date object alone does not know whether it should be displayed as 'mm-dd-yy' or 'dd/mm/yy'. F.ex 一个原始日期 object 单独不知道它应该显示为“mm-dd-yy”还是“dd/mm/yy”。 For this you need the "number format string", which is ignored by AsDataSet() .为此,您需要“数字格式字符串”,它被AsDataSet()忽略。

To work around this, instead of calling AsDataSet() , you need to manually loop over the rows/columns using ExcelDataReader's lower level reader APIs, and using the third party library ExcelNumberFormat to format the values like Excel.要解决此问题,您需要使用 ExcelDataReader 的较低级别读取器 API 手动循环行/列,并使用第三方库ExcelNumberFormat来格式化 Excel 等值,而不是调用AsDataSet()

This relevant snippet from their readme shows how to format a single value from the reader object:他们自述文件中的相关片段显示了如何格式化来自阅读器 object 的单个值:

string GetFormattedValue(IExcelDataReader reader, int columnIndex, CultureInfo culture)
{
    var value = reader.GetValue(columnIndex);
    var formatString = reader.GetNumberFormatString(columnIndex);
    if (formatString != null)
    {
        var format = new NumberFormat(formatString);
        return format.Format(value, culture);
    }
    return Convert.ToString(value, culture);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM