How do I create and parse a true Excel Compatible CSV file? Excel is very particular about how it creates and parses CSV files. Some folks have the idea that Excel encloses all fields in double quotes when it creates a comma delimited file. At least with Excell 2003, that's not exactly true; in fact, not even close.
In a ASP.NET Web Application that I am working on, I had to export and import CSV files from/to database. I found that my own concept of what Excel does in certain situations varies based on the presence of commas and double quotes, on both the Import and Export in Excel. After testing numerous configurations of data in spreadsheet fields I found that the rule of thumb for creating a spreadsheet that Excel will load properly, is this. If a field has one or more quotes (") in it, the number of quotes should be doubled. Secondly, having taken care of that for each field, if the resultant field contains a quote or a comma, the field should be enclosed in double quotes. Figure 1 will show the code for creating the proper quoting of fields for a CSV.
Figure 1 - Quoting Fields For Writing CSV.
| foreach (DataRow dr in dt.Rows) { string line = QuoteFieldAsRequiredByExcel(dr["FName"].ToString().Trim()) + comma + QuoteFieldAsRequiredByExcel(dr["LName"].ToString().Trim()) + comma + QuoteFieldAsRequiredByExcel(dr["PhoneNumber"].ToString().Trim()) + Environment.NewLine; Response.Write(line); } // foreach |
| /// if a field contains a " or , the rule is that /// all quotes are doubled and the field is inclosed in quotes private string QuoteFieldAsRequiredByExcel(string field) { string retValue = field.Replace("\"", "\"\""); if (field.IndexOf(",") > -1 || field.IndexOf('"') > -1) { return "\"" + retValue + "\""; } // if else { return field; } // else } // method: QuoteFieldWithComma |
| string[] lineArray = null; Regex re = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"); using (StreamReader sr = new StreamReader(VSFileName)) { string line = sr.ReadLine(); sr.Close(); lineArray = re.Split(line); foreach (string field in firstFields) { ddlFirstNames.Items.Add(field.Replace("\"", "").Trim()); } // foreach } |
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. | ![]() |