且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 IExcelDataReader 值转换为字符串数据类型

更新时间:2023-01-30 17:49:50

使用非 LINQ 版本的扩展添加到@AlwaysLearning 答案.

Adding to @AlwaysLearning answer with a non LINQ version of the extension.

public static class DataSetExtensions
{
    public static DataSet ToAllStringFields(this DataSet ds)
    {
        // Clone function -> does not copy the data, but just the structure.
        var newDs = ds.Clone();
        foreach (DataTable table in newDs.Tables)
        {
            // if the column is not string type -> set as string.
            foreach (DataColumn col in table.Columns)
            {
                if (col.DataType != typeof(string))
                    col.DataType = typeof(string);
            }
        }

        // imports all rows.
        foreach (DataTable table in ds.Tables)
        {
            var targetTable = newDs.Tables[table.TableName];
            foreach (DataRow row in table.Rows)
            {
                targetTable.ImportRow(row);
            }
        }

        return newDs;
    }
}

用法:

public DataSet ReadExcelDataToDataSet(Stream fileStream)
{
    DataTable dataInExcelSheet = new DataTable();
    IExcelDataReader excelReader = ExcelReaderFactory.CreateReader(fileStream);
    DataSet excelDataSet = excelReader.AsDataSet(new ExcelDataSetConfiguration()
    {
        UseColumnDataType = false
    }).ToAllStringFields();
    excelReader.Close();
    return excelDataSet;
}