首页 > 解决方案 > 如何将 IExcelDataReader 值转换为字符串数据类型

问题描述

我正在使用下面的代码来读取 Excel 并存储在数据集中。

     public DataSet ReadExcelDataToDataSet(Stream fileStream)
            {
                DataTable dataInExcelSheet = new DataTable();
                IExcelDataReader excelReader = ExcelReaderFactory.CreateReader(fileStream);
                DataSet excelDataSet = excelReader.AsDataSet(new ExcelDataSetConfiguration()
                {
                    UseColumnDataType = false
//Do we have any property here to convert all rows values to string datatype.
                });
                excelReader.Close();
                return excelDataSet;
            }

有没有办法将 Excel 工作表的所有值转换为字符串并将其作为字符串值存储在数据集中。

例子:

在 Excel 文件中,对于少数列,我的值为 1,22.0,它们属于 Int32 和 Double 数据类型。我想将这些值转换为字符串,然后将它们作为字符串存储在数据集中。

标签: c#.net.net-coreexceldatareader

解决方案


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

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

推荐阅读