DEV Community

bristolsamo
bristolsamo

Posted on

How to read a CSV File in C# (Step by Step Tutorial)

a miles easier manner to have your software percentage information is by analyzing and writing Comma-Separated Values (CSV) documents. CSV files can without difficulty be examined and written with the aid of many programs, including Microsoft Excel.

For the top part, studying and writing CSV files is trivial. Because of the call suggestions, a CSV document is virtually a simple textual content file that includes one or more values in step with the line, separated by commas. Each fee is a subject (or column in a spreadsheet), and every line is a report (or row in a spreadsheet).

But, there are slightly more paintings concerned. Double fees are used to wrap values that incorporate commas so that the commas aren't interpreted as a cost separator. The equal is also performed for values that contain double prices. In addition, double fees collectively characterize a double quote within the fee and not a fee separator.

Working with numerous Excel codecs often requires reading facts, reconfiguring them programmatically. In this article, we can learn how to study a CSV record and parse records from an Excel spreadsheet in C# using IronXL, the precise tool for the job.

What are CSV files?

CSVs (Comma Separated Values) are famous import and export information codecs utilized in spreadsheets and databases. Usually, statistics are saved on one line and separated using commas. It's miles essential to use our CSV assist package for our initiatives. CSV is a simple information layout, but there can be many differences. Those might also encompass one-of-a-kind delimiters, new lines, or costs. It's miles possible to study and Write CSV data with the assistance of the CSV help library.

Load Workbook and Access Worksheet

The workBook is the magnificence of IronXL, whose item presents complete get entry to the Excel record and all of its features. For instance, if we want to get an entry to an Excel file, we would use the code:



WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path


Enter fullscreen mode Exit fullscreen mode

To get admission to the precise WorkSheet of an Excel document, IronXL presents the WorkSheet class.



WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name


Enter fullscreen mode Exit fullscreen mode

Once you've received the ExcelSheet ws, you can extract any kind of information from it and perform all Excel functions. data can be accessed from the ExcelSheet ws on this method:



using IronXL;
static void Main(string[] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
   WorkSheet ws = wb.GetWorkSheet("Sheet1");
   foreach (var cell in ws["A2:A10"])
   {
       Console.WriteLine("value is: {0}", cell.Text);
   }
   Console.ReadKey();
}



Enter fullscreen mode Exit fullscreen mode

The foreach var is used to loop across each cell in the workbook, and the values are stored in a string array.

How to read a CSV file in c# and store data as var values

if you have CSV documents rather than an excel report, you have to make slight adjustments to the code to read a CSV file.

Allow's to examine the subsequent instance.

I have the same weather record saved as "weather.csv," so I'm using the equal report for all the examples. Again, you could use an example in keeping with your necessities.



 WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
    WorkSheet ws = workbook.DefaultWorkSheet;
    workbook.SaveAs("Csv_To_Excel.xlsx");


Enter fullscreen mode Exit fullscreen mode

The primary line will load the CSV file and outline the document layout. The second one line will pick out the worksheet simultaneously as the alternative code strains are similar to those inside the preceding examples. Each CSV file line is a var line; the foreach is used to loop over each variable line using the var reader. The read data is then stored in a var path.

OUTPUT

the read row is the first row in the CSV file is the header row. All the rows are displayed on a separate line.
Image description

A Workbook item is created. The LoadCSV technique for the Workbook object is then used to specify the call of the CSV, its format, which delimiters are used in the CSV file being examined to separate var row. In this case, commas are used as delimiters.

A Worksheet object is then created; This is where the contents of the CSV file might be placed. Then the file is saved beneath a brand new call and layout.
Image description

How to use a CSV parser in C#

to use a parser, you need first to read a CSV file. CSVs have an abundance of troubles with how line breaks are handled in fields or how fields can be contained in fees that block a simple string break-up method. I've lately discovered the following options while converting CSV files to C# files. Internet: it's the first time I've ever used simply one string.split(') instead of an easy. Strings.cutup() to split the values in a comma. In this article, we can look at the great ways in which C++ has a CSV parser feature in C.XcPC.internet.

It is simple to create a CSV parser. With the most effective lines of code, you could load a CSV file and convert it to Excel.



private void button4_Click(object sender, EventArgs e)
{
    WorkBook wb = WorkBook.Load("Normal_Excel_File.xlsx"); //Import .xls, .csv, or .tsv file
    wb.SaveAs("Parsed_CSV.csv"); //Exported as : Parsed_CSV.Sheet1.csv
}


Enter fullscreen mode Exit fullscreen mode

After you have set up IronXL, create a brand new project and add the IronXL namespace



using IronXL;


Enter fullscreen mode Exit fullscreen mode

1. Load a CSV record into Excel

the following code uses the Workbook object's Load approach to load a comma-separated CSV file into Excel. The CSV is read as a string array containing string columns. This document is then parsed. finally, it uses the SaveAs method to keep the file within the CSV file format.



private void button4_Click(object sender, EventArgs e)
{
    WorkBook wb = WorkBook.Load("Normal_Excel_File.xlsx"); //Import .xls, .csv, or .tsv file
    wb.SaveAs("Parsed_CSV.csv"); //Exported as : Parsed_CSV.Sheet1.csv
}



Enter fullscreen mode Exit fullscreen mode

2. Export the Parsed CSV

The exported CSV file will be stored as Parsed_CSV.Sheet1.csv because the records are on Sheet1 inner of the Excel Workbook. Under what the file would appear like in the report Explorer when selected. This export is done by reading the store data in the var path.

Parsing records using StreamReader

The first test is to make sure the record to parse exists. Inside the following code block, mHasException and mLastException are from a base exception elegance which the class for parsing inherits. The go-back kind is a ValueTuple (established the usage of NuGet package deal supervisor).



if (!File.Exists(_inputFileName))
{
    mHasException = true;
    mLastException = new FileNotFoundException($"Missing {_inputFileName}");
    return (mHasException, new List<DataItem>(),new List<DataItemInvalid>() );
}


Enter fullscreen mode Exit fullscreen mode

If the document exists the subsequent step is to set up several variables for you to be used for validation functions and go back sorts in an effort to comprise legitimate and if presented invalid statistics while examine in information from the CSV record.



var validRows = new List<DataItem>();
var invalidRows = new List<DataItemInvalid>();
var validateBad = 0;

int index = 0;

int district = 0;
int grid = 0;
int nCode = 0;
float latitude = 0;
float longitude = 0;



Enter fullscreen mode Exit fullscreen mode

*Reading CSV Data in C# Records
*

This process advances the reader through the following document. We study the comma-separated file CSV discipline files in trygetfield. We use the study feature on the subject fields of the CSV files as report fields.

The following example shows how it is done.

The foreach var values read each string in the CSV file, converted to a tabular form, and a new record is created. The first string of the CSV file is known as the public string.

Double quotes are used to delimit strings.



WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
            WorkSheet ws = workbook.DefaultWorkSheet;
    DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
            foreach (DataRow row in dt.Rows) //access rows
            {
         for (int i = 0; i < dt.Columns.Count; i++) //access columns of corresponding row
                {
                    Console.Write(row[i] + "  ");
                }
                Console.WriteLine();
            }


Enter fullscreen mode Exit fullscreen mode

The output produces a string line which is displayed as follows.
Image description

Save Workbook to CSV file

we can convert an excel workbook into a CSV file by converting the tabular form string rows separated by commas. The following code uses the Workbook object's Load approach to load a record into Excel.

Then, it uses the SaveAs method to store data in the CSV file within the preferred layout - in this example.csv.

What's thrilling here is that it appends the worksheet's name onto the filename, which is a quite nifty reminder of where the statistics are coming from.

the source code below is a perfect example.



private void button3_Click(object sender, EventArgs e)
{
    WorkBook wb = WorkBook.Load("Normal_Excel_File.xlsx"); //Import .xls, .csv, or .tsv file
    wb.SaveAs("Excel_To_CSV.csv"); //Exported as : Excel_To_CSV.Sheet1.csv
}


Enter fullscreen mode Exit fullscreen mode

The output CSV file seems like the following while opened in an everyday text Editor, including Notepad.
Image description

How to Use C# to Convert Datatable to CSV file

you could export a data table to a comma-separated file CSV with IronXL using taking an existing facts table and changing it to a CSV file in only some steps. this newsletter goal is to reveal to you a short instance of this

First, import the IronXL namespace



using IronXL;


Enter fullscreen mode Exit fullscreen mode

Then, add the following code:



private void button6_Click(object sender, EventArgs e)
{
    DataTable table = new DataTable();
    table.Columns.Add("Example_DataSet", typeof(string));
    table.Rows.Add("0");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
    wb.Metadata.Author = "OJ";
    WorkSheet ws = wb.DefaultWorkSheet;
    int rowCount = 1;
    foreach (DataRow row in table.Rows)
    {
        ws["A" + (rowCount)].Value = row[0].ToString();
        rowCount++;
    }
    wb.SaveAsCsv("Save_DataTable_CSV.csv", ";"); // Saved as : Save_DataTable_CSV.Sheet1.csv
}



Enter fullscreen mode Exit fullscreen mode

The above code creates a statistics desk and a brand new workbook specifying 'OJ' as its owner/writer. A foreach var loop follows that inserts the records from the facts table into the Excel Worksheet. Lastly, the SaveAsCsv technique exports the data table to a CSV file.

The pointer moves from one line to the following line using a foreach var or a new streamreader. Each row is read as a new string and is attributed as a string name; the first line of the CSV file is read as the string column that contains the string column names.

You could download the software program product from this hyperlink.

The output Excel Worksheet appears as follows:
Image description

C# Export from CSV to .XLSX File

IronXL affords the maximum on-hand way to export the data to Excel with ( .xls, .xlsx and .csv) documents in .net programs. it's also viable to export the records to .json and .xml documents. let's see one after the other how clean it may be to export Excel document statistics into these codecs.

First, you need to read a CSV file; it's straightforward to export an Excel report with a .xlsx extension. Let's see the instance. in the code underneath; our XlsFile.xls report exists in bin>Debug folder of the challenge.

Consider: take into account writing down an extension with document call simultaneously as importing or exporting.

By default, new Excel documents will be created within the bin>Debug folder of the task. If we want to create a brand new report in a custom path, we will use `


wb.SaveAs(@"E:IronXLNewXlsxFile.xlsx");

`. examine the tutorial here to examine greater approximately how to export Excel files in .internet.



using IronXL;
static void Main(string[] args)
{
    WorkBook wb = WorkBook.Load("XlsFile.xls");//Import .xls, .csv, or .tsv file
    wb.SaveAs("NewXlsxFile.xlsx");//Export as .xlsx file
}


Enter fullscreen mode Exit fullscreen mode

Further to CSV parsing in C#, IronXL converts CSVs to Excel with just two strains of code!

The usage of C# it's far very smooth to use IronXL's Excel API without the want for Interop. You can examine, edit, and create Excel spreadsheets or work with different Excel codecs consisting of XLS/XLSX/CSV/TSV. With the assistance of a couple of frameworks, you could purchase five merchandise for the fee of two. Click on here for similar information.

IronXL license keys permit you to deploy your mission stay with no watermark.

Licenses start at just $499 and encompass one free 12 months of help and updates.

With a trial license key, you may also strive for IronXL loose for 30 days.

Iron software offers you the possibility to seize their complete package at a lower fee.

The iron software suite comprises five additives IRONPDF, IRON XL, IRONOCR, IRONBARCODE, and the IRONWEBSCRAPER.

You may get the whole bundle at the most exact percent price by paying in one installment.

It's undoubtedly a possibility worth going for.

You can download the software product from this link.

Top comments (0)