【发布时间】:2022-01-04 08:31:28
【问题描述】:
我正在尝试从 csv 文件中填充数据表读取值。数据表的格式应与数据库中对应的表相匹配。
csv 文件有很多列 (~80),所以我不想输入所有内容。 csv 文件中的列名与 db 中的列名不完全匹配。此外,必须手动添加两个额外的列,其中 csv 中不存在数据。
问题是将csv文件中的字符串数据转换为数据表中的正确类型。
目前我有
-
我从数据库中读取表格模板并使用它来创建我的新数据表。
-
我创建了一个映射,将 csv 文件中的列位置映射到数据库中的列位置。
-
我尝试将 csv 文件中的值插入到数据表中。这是我的代码失败的地方,因为数据的类型不正确。如上所述,由于有很多不同的列,我不想手动进行转换,而是从表格模板中推断出类型。此外,某些列可以包含空值。
我的代码
public static DataTable ReadAssets(string strFilePath, DateTime reportingDate, Enums.ReportingBases reportingBasis, char sep=',')
{
//Reads the table template from the database
DataTable dt = DbInterface.Db.GetTableTemplate("reports.Assets");
var dbColumnNames = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();
//These columns are not present in the csv data and so they have to be added manually
int posReportingDate = dbColumnNames.IndexOf("ReportingDate");
int posReportingBasis = dbColumnNames.IndexOf("ReportingBasis");
//read the csv and populate the table
using (StreamReader sr = new (strFilePath))
{
string[] csvColumnNames = sr.ReadLine().Split(sep);
//creates an <int, int> dictionary that maps the columns
var columnMap = CreateColumnMap(dbColumnNames.ToArray(), csvColumnNames);
while (!sr.EndOfStream)
{
string[] csvRow = sr.ReadLine().Split(sep);
DataRow dr = dt.NewRow();
dr[posReportingDate] = reportingDate;
dr[posReportingBasis] = reportingBasis.ToString();
foreach(var posPair in columnMap)
{
//This is where the code fails.... I need a conversion to the correct type here.
dr[posPair.Value] = csvRow[posPair.Key];
}
dt.Rows.Add(dr);
}
}
return dt;
}
【问题讨论】:
-
我认为你可以使用
dr[posPair.Value] = Convert.ChangeType(csvRow[posPair.Key], dbColumn.DataType);之类的东西。可以从DataColumn获取数据类型。 -
@ekke 嗨,谢谢。那几乎做到了。它似乎无法处理可空类型...