c# - 如何将 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 数据类型。我想将这些值转换为字符串,然后将它们作为字符串存储在数据集中。
解决方案
使用扩展的非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;
}
推荐阅读
- java - Appium:无法运行 web 移动 chrome 浏览器脚本
- php - php laravel/vuejs 部署我的 vuejs 视图没有呈现
- php - 清除 PHP 回显值输入字段
- ios - 在 childViewControllers Swift 之间传递数据
- c# - 如何将 Asp.net core SPA(单页应用程序)和 Asp.net core Web Application 合并到一个单独的项目中
- angularjs - 在服务中注册一个回调函数,当服务使用 TypeScript 在 AngularJs 中触发回调时调用该函数
- sql-server - SQL Server 将数据库复制到不同的服务器
- python - Django ModelForm 继承和 Meta 继承
- asp.net - 如何使用角度中的点击标签重定向页面
- selenium - 如何以特定顺序从 xml 文件运行测试