After creating the extension method of DataTableToExcel, let’s create that DataTable from a CSV file.
If you open a csv file in Excel, you’ll get all the information in 1 column. Now we create a usable xlsx file from out csv.
DataTable dt = new DataTable(); char separation = ',';//comma separated csv //columns string[] columns = fileContent[0].Split(separation); for (int i = 0; i < columns.Count(); i++) { dt.Columns.Add(columns[i].Replace("\"", ""));//if the column name contains DoubleQuotes, let's remove it } //rows for (int i = 1; i < fileContent.Count(); i++) { string[] rowData = fileContent[i].Split(separation); string[] realRowData = new string[columns.Count()]; StringBuilder finalString = new StringBuilder(); int temp = 0; for (int j = 0, k = 0; j < rowData.Count(); j++, k++) { if ((rowData[j].Count(x => x == '"') % 2 == 0))//checks if the string contains EVEN number of DoubleQuotes { realRowData[k] = quotesLogic((rowData[j])); } else if ((rowData[j].Count(x => x == '"') % 2 != 0))//If Number of DoubleQuotes are ODD { int c = rowData[j].Count(x => x == '"'); temp = j; while (c % 2 != 0)//Go through all the next array cell till it makes EVEN number of DoubleQuotes. { finalString.Append(rowData[j] + ","); j++; c += rowData[j].Count(x => x == '"'); } finalString.Append(rowData[j]); realRowData[k] = quotesLogic(finalString.ToString()); } else continue; } if (realRowData[0].Trim() != "") dt.Rows.Add(realRowData);//if we have empty rows in Excel, we're gonna skip them }
Now if you set this DataTable as source of a DataGridView, you’ll get a perfect table structure.