如何将IExcelDataReader值转换为字符串数据类型 [英] How to convert IExcelDataReader Values to string Datatype
本文介绍了如何将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的所有值转换为字符串并将其存储在数据集中作为字符串值。
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.
推荐答案
添加到@AlwaysLearning答案中,带有非 LINQ
版本的扩展。
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屋!
查看全文