我有CSV文件,其中包含大约25列和100行。
我正在尝试验证行的每一列,如果失败,我想创建一个包含行号,列名失败等的表,并在所有行处理后显示它。
这方面的任何线索都可以吗?我怎样才能做到这一点? 以下是代码:
protected void ValidateData_Click(object sender , EventArgs e )
{
//Upload and save the file
string filePath = Server.MapPath("~/Files/") + Path.GetFileName(UploadFile.PostedFile.FileName);
UploadFile.SaveAs(filePath);
//read and validate csv file
ValidateCsv(filePath);
}
//Validate CSV file
private void ValidateCsv(string fileContent)
{
DataTable getCSVData;
getCSVData=GetData(fileContent);
ValidateRows(getCSVData);
}
//get data from csv
private DataTable GetData(string fileContent)
{
//read csv file
DataTable dataTable = new DataTable();
using (StreamReader reader = new StreamReader(fileContent))
{
string[] headers = reader.ReadLine().Split(',');
foreach (string header in headers)
{
dataTable.Columns.Add(header);
}
while (!reader.EndOfStream)
{
string[] csvRow = reader.ReadLine().Split(',');
DataRow dataRow = dataTable.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dataRow[i] = csvRow[i];
}
dataTable.Rows.Add(dataRow);
}
}
return dataTable;
}
//validate Rows
private void ValidateRows(DataTable csvDataTable)
{
}
由于
答案 0 :(得分:1)
这是一个可用于验证方法的超级基本结构。
private void ValidateRows(DataTable csvDataTable)
{
DataTable invalidatedTable = new DataTable();
// If you only want certain columns in the datatable do this for each.
DataTable invalidatedTable = new DataTable();
invalidatedTable.Columns.Add("ColumnName", typeof(string));
// If you want all the columns in the new datatable that are in the source then do this.
DataTable invalidatedTable = csvDataTable.Clone();
// Loop over all the rows in the datatable
foreach (DataRow row in csvDataTable.Rows)
{
bool invalidated = false;
// Check if id column is null
if (row["id"] == null)
invalidated = true;
// Check some other column is not equal to some value
if (row["columnName"].ToString() != "Whatever you consider valid")
{
invalidated = true;
}
// If you'd like to loop through the columns instead...
foreach (DataColumn column in csvDataTable.Columns)
{
if (row[column] != SomeTest)
{
invalidated = true;
}
}
// if any of the rules above marked this row as invalid then add to table
if (invalidated)
{
// this will add a copy of the entire row from the original table
invalidatedTable.Rows.Add(row.ItemArray);
// if instead you'd like to edit the data first then do this
// Note: Depending on your data structure you may need to add nulls or values
// to columns to keep your tables with the same structure.
DataRow invalidRow = invalidatedTable.NewRow()
invalidRow["columnName"] = "someValue"
invalidatedTable.Rows.Add(invalidRow);
}
} // End Loop
// Show the invalid rows on a form control
SomeFunctionThatBindsDatatableToFormControl(invalidatedTable);
}
根据您的具体需求,有许多方法可以修改,改进等,但希望这可以让您至少开始。