Alex Gordon
Alex Gordon

Reputation: 60731

How to enforce untyped columns in ExcelDataReader?

How do you prevent dates or times getting strictly-formatted?

I'm reading an XLS file using reader.AsDataSet, and when the source data is 12/12/2014 then this generates an output of 12/12/2014 12:00:00AM.

Also, when the source is for example 5:01:23 AM then this generates something weird: 12/31/1899 5:01:23 AM

Here's the function:

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

How do we read in the XLS file into a DataSet without automatically typing-concretely the data?

Upvotes: 0

Views: 1805

Answers (1)

shA.t
shA.t

Reputation: 16958

I think in this situation you have all data you need in your result (as DataSet)!
So, I can suggest you to ignore that option in reading time and instead add any extra column to your result like below:

// `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

Upvotes: 1

Related Questions