Hi!
I have a program that can export datagridview to csv.
All works well and all but one problem has occured.
The created csv file has two extra rows that are empty and they are causing me some trouble.
How can I get rid of them when exporting. Trimming them of in notepad is not really an option.
My code for the export looks like this:
- private void btnExport_Click(object sender, EventArgs e)
- {
-
- if (dataGridView1.Rows.Count == 0)
- {
- return;
- }
- StringBuilder sb = new StringBuilder();
- sb.AppendLine(string.Join(",", dataGridView1.Columns.Cast().Select(x => $"\"{x.Name}\"")));
- foreach (DataGridViewRow row in dataGridView1.Rows)
- {
- if (!row.IsNewRow)
- {
- sb.AppendLine(string.Join(",", row.Cells.Cast().Select(c => $"\"{c.Value ?? ""}\"")));
- }
- }
-
- SaveFileDialog sfd = new SaveFileDialog();
- sfd.Filter = "CSV files (*.csv)|*.csv";
- if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
-
- using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))
- {
-
- sw.WriteLine(sb.ToString());
- }
- }
All help is appreciated, Thanks.
-Matti