Goal: Search through a specific single column in a CSV for empty rows only in that column and replace with string "No Box".
Attempts: So far I have tried to use CsvHelper and CsvTools(CsvReader) via Nuget C#. I am not very experienced with C# so not sure how to accomplish my task. Searching did not turn up any examples or references that helped me understand what I need to implement. There are a lot of similar questions, but none of them searched a specific column. I am hoping someone can provide me with advice on how to get my for loop to work and get the number of rows for my checking.
Image sample of my CSV file. Sample of CSV data column Site
private static void SiteBlanks()
{
try
{
MutableDataTable dt = DataAccess.DataTable.New.ReadCsv(@"C:\temp.csv");
for (int i = 0; i <= dt.Rows.Count; i++) // Cannot be applied to data types, so this errors.
{
if (!string.IsNullOrEmpty(dt.GetRow(i)["Site"])) // Check if cells in column 1 are empty
{
dt.Columns[1].Values[i] = "No Box"; // Update empty values with No Box
}
}
dt.SaveCSV(@"C:\temp.csv"); // Save file after changes.
}
catch (Exception ex)
{
//Set Error message
Error("ERROR: SiteBlanks()", ex);
}
}
Note: This is my first question ever asked so be gentle and tell me what I may have did wrong posting wise.
Based on your current code you can try the following
private static void SiteBlanks() {
try {
string filePath = @"C:\temp.csv";
MutableDataTable dt = DataTable.New.ReadCsv(filePath);
string columnName = "Site";
var numberOfRows = dt.NumRows ;
for (int i = 0; i < numberOfRows; i++) {
var row = dt.GetRow(i);
if (string.IsNullOrEmpty(row[columnName])) {
row[columnName] = "No Box";
}
}
dt.SaveCSV(filePath);
} catch (Exception ex) {
//Set Error message
Error("ERROR: SiteBlanks()", ex);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.