如何将 IExcelDataReader 值转换为字符串数据类型 [英] How to convert IExcelDataReader Values to string Datatype

查看:35
本文介绍了如何将 IExcelDataReader 值转换为字符串数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码读取 Excel 并存储在数据集中.

I am using below code to read Excel and store in Dataset.

     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 Sheet的所有值都转换成字符串,并作为字符串值存储在Dataset中.

Is there any way to convert all values of Excel Sheet to string and store it in Dataset as String values.

示例:

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

In Excel file, for few columns I have values as 1,22.0 which are of Int32 and Double datatypes. I want to convert these values to string and then store them in Dataset as String.

推荐答案

使用非 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;
}

这篇关于如何将 IExcelDataReader 值转换为字符串数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆