Creating CSV using Custom Rows
using(var csvBuilder = CsvBuilder.Datasets(
new List
{ "SR.", "Name", "Gender","Phone Number" }, new List
{ "1", "Test Test" }, new List
{ "2", "Test Male 1", "Male" }, new List
{ "2", "Test Female 1", "Female","+09298374" }).Build()){
csvBuilder.SaveAsFile("Greate.csv");
}
CsvBuilder.Datasets(...)
: This is a static factory method of the CsvBuilder
class. It creates an instance of CsvBuilder
using the provided data. The data is passed as lists of strings, where each list represents a row in the CSV. The first list is assumed to contain the header/column names.
using (...)
: The using
statement is used to ensure that the csvBuilder
object is properly disposed of when it goes out of scope. This is important because the CsvBuilder
class implements IDisposable
and works with resources (a MemoryStream
in this case). The using
statement ensures that the Dispose
method is called when the block is exited, releasing any resources held by csvBuilder
.
csvBuilder.Build()
: This method is called on the csvBuilder
instance to construct the CSV data. It takes an optional array of column indices to be included in the CSV. In this case, no specific columns are selected, so it includes all columns.
csvBuilder.SaveAsFile("Great.csv")
: This method is called to save the generated CSV data to a file named "Great.csv". The SaveAsFile
method takes a file path as a parameter.
Creating three DataTable instances (dataTableFilter, companyInfo, and actualDataset), populating them with data, and then using the CsvBuilder class to generate and save a CSV file. Let's break down the code:
DataTable dataTableFilter = new DataTable("SampleDataFilters");
//Add the column names
dataTableFilter.Columns.Add("column1", typeof(string));
dataTableFilter.Rows.Add("All Customers");
dataTableFilter.Rows.Add("Search Filter");
dataTableFilter.Rows.Add("Customer Type: All");
dataTableFilter.Rows.Add("Customer Status: Active");
dataTableFilter.Rows.Add("From: 03 - 01 - 2022 To: 03 - 11 - 2023");
DataTable companyInfo = new DataTable("company");
//Add the column names
companyInfo.Columns.Add("column1", typeof(string));
companyInfo.Rows.Add("London");
companyInfo.Rows.Add("Add01a, City");
companyInfo.Rows.Add("London, sef83n");
companyInfo.Rows.Add("T: +441234567890");
companyInfo.Rows.Add("E:");
DataTable actualDataset = new DataTable("SampleDataActual");
actualDataset.Columns.Add("Sr.", typeof(int));
actualDataset.Columns.Add("Branch", typeof(string));
actualDataset.Columns.Add("Branch Code", typeof(int));
actualDataset.Columns.Add("Name", typeof(string));
actualDataset.Columns.Add("Email", typeof(string));
actualDataset.Columns.Add("Mobile", typeof(long));
actualDataset.Columns.Add("Membership Created Date", typeof(string));
actualDataset.Rows.Add(1, "Branch 1", 82, "Alex Will", "Alw@yopmail.com", 44578963219, "18.02.2022 - 11:00AM");
actualDataset.Rows.Add(2, "Branch 1", 82, "eqw Will", "eqw@yopmail.com", 4324, "18.02.2022 - 11:00AM");
actualDataset.Rows.Add(3, "Branch 1", 82, "eqw Will", "32@yopmail.com", 4455353478963219, "18.02.2022 - 11:00AM");
using (var csvBuilder = CsvBuilder.Datasets(dataTableFilter, companyInfo, actualDataset).Build(2))
{
csvBuilder.SaveAsFile("Greate.csv");
}
DataTable
Creation and Population: You create three DataTable
instances (dataTableFilter
, companyInfo
, and actualDataset
) and add columns and rows to them.
CsvBuilder.Datasets(...)
: You use the CsvBuilder
class to create an instance and pass the three DataTable
instances as parameters.
.Build(2)
: You call the Build
method on the CsvBuilder
instance, specifying that only the columns with index 2 should be included in the CSV.
csvBuilder.SaveAsFile("Great.csv")
: You save the generated CSV data to a file named "Great.csv".
var builder = CsvBuilder.Datasets(filters, companyInformation, actualDataSet, calculationDataset);
// Here, you're creating an instance of the CsvBuilder class using the Datasets method,
// and you're passing four DataTable instances (filters, companyInformation, actualDataSet,
// and calculationDataset) as parameters.
builder.ValueRenderEvent += (val, type, column, row, tableIndex, actualRowNumber) =>
{
if (tableIndex == 2 && column == 1 && row >= 2)
{
return (row - 1).ToString();
}
return $"\"{Convert.ToString(val).Replace("\"", "\"\"")}\"";
};
You're subscribing to the ValueRenderEvent event of the CsvBuilder instance (builder). This event is raised when the CSV data is being rendered for each value. The event handler is implemented as a lambda expression.
if (tableIndex == 2 && column == 1 && row >= 2)
: This condition checks if the current value belongs to the second table (tableIndex == 2
), is in the first column (column == 1
), and is not in the header row (row >= 2
). If these conditions are met, it returns the modified value (row - 1).ToString()
. This logic seems to be adjusting the values in the first column for the second table, subtracting 1 from the row number.
return $"\"{Convert.ToString(val).Replace("\"", "\"\"")}\"";
: For other cases, it returns the original value enclosed in double quotes, and it handles escaping double quotes within the value by replacing them with double double-quotes (\"\"
).The code snippet showcases the creation of a CSV builder with custom options and data rows, emphasizing header presence, initial row skipping, and a specialized condition for skipping specific rows. Two distinct data sets are represented in the provided data rows, marked by "start" and "end" identifiers. The resulting CSV extractor is then used to save the generated CSV data to a file named "data.csv."
// Creating a CSV builder with specified options and data rows
var extractor = CsvBuilder.Datasets(new Options
{
HeaderMode = HeaderMode.HeaderPresent, // Specify that the CSV data has a header
SkipInitialNumberOfRows = 2, // Skip the first two rows during CSV building
SkipRow = (v, rowIndex) => v.Contains("start") || v.Contains("end")
// Define a custom row skipping condition based on row content
},
// Data rows for building the CSV
new List
{ "start#1" }, // Start of data set #1
new List
{ "Data", "Data2" }, // Header row for data set #1
new List
{ "Data1", "Data21", "Data331", "Data31" }, // Data rows for data set #1
new List
{ "end#1" }, // End of data set #1
new List
{ "start#2" }, // Start of data set #2
new List
{ "Data1", "Data21", "Data331", "Data31" }, // Data rows for data set #2
new List
{ "Data1", "Data21", "Data331", "Data31" } // Data rows for data set #2
).Build(); // Build the CSV extractor
// Saving the CSV data to a file named "data.csv"
extractor.SaveAsFile("data.csv");