如何在ExcelDataReader中强制执行无类型的列?

时间:2018-11-21 17:07:02

标签: c# type-conversion dataset xls exceldatareader

如何防止日期或时间格式严格?

我正在使用reader.AsDataSet读取XLS文件,并且当源数据为12/12/2014时,这将生成12/12/2014 12:00:00AM的输出。

此外,例如当来源为5:01:23 AM时,这会产生一些奇怪的内容:12/31/1899 5:01:23 AM

功能如下:

using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    IExcelDataReader reader = null;
    if (excelFilePath.EndsWith(".xls"))
    {
        reader = ExcelReaderFactory.CreateBinaryReader(stream);
    }
    else if (excelFilePath.EndsWith(".xlsx"))
    {
        reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
    }

    if (reader == null)
        return false;

    var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
    {
        UseColumnDataType = false,
        ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
        {
            UseHeaderRow = false
        }
    });

我们如何将XLS文件读入数据集而又不自动直接键入数据?

1 个答案:

答案 0 :(得分:1)

我认为在这种情况下,您拥有结果中所需的所有数据(为DataSet)!
因此,我建议您在阅读时忽略该选项,而应在结果中添加任何额外的列,如下所示:

// `Copy` used to generate a new object
var dataTable = ds.Tables[0].Copy();

// create a new column with your own settings (like `TimeOnly`) and add it to your new DataTable
var newColumn = new DataColumn("TimeOnly", typeof(string)) { AllowDBNull = true };
dataTable.Columns.Add(newColumn);

// update your new column data based on other columns like `Column1`
foreach (DataRow row in dataTable.Rows)
{
    var value = DateTime.Parse(row["Column1"].ToString()).ToString("HH:mm:ss");
    row["TimeOnly"] = value;
}

HTH