0

I use next code to export data from datagridView into xls file.

private void ToCsV(DataGridView dGv, string filename)
{
    var stOutput = "";
    // Export titles:
    var sHeaders = "";

    for (var j = 0; j < dGv.Columns.Count; j++)
        sHeaders = sHeaders + Convert.ToString(dGv.Columns[j].HeaderText) + "\t";

    stOutput += sHeaders + "\r\n";
    // Export data.
    for (var i = 0; i < dGv.RowCount - 1; i++)
    {
        var stLine = "";
        for (var j = 0; j < dGv.Rows[i].Cells.Count; j++)
        stLine = stLine + Convert.ToString(dGv.Rows[i].Cells[j].Value) + "\t";

        stOutput += stLine + "\r\n";
    }

    var utf16 = Encoding.GetEncoding(1254);
    byte[] output = utf16.GetBytes(stOutput);
    var fs = new FileStream(filename, FileMode.Create);
    var bw = new BinaryWriter(fs);
    bw.Write(output, 0, output.Length); //write the encoded file
    bw.Flush();
    bw.Close();
    fs.Close();
}  

As result i get "bad" formated file :

xls-file

I don't know why file content is like this (some text aren't in right columns). Any suggestion? Thanks.


Is it possible because some text for cell has "newLine" \n ?

Robert Messerle
  • 3,022
  • 14
  • 18
demo
  • 6,038
  • 19
  • 75
  • 149

1 Answers1

0

Enclose all your values (or at least the ones being a potential issue) with double quotes. Instead of 123\n put "123\n" in your csv file.

This issue is most of the time encountered when using decimal separator in csv files, like explained here. Your \n case looks a lot alike.

Community
  • 1
  • 1
Askolein
  • 3,250
  • 3
  • 28
  • 40
  • And one More... what you can suggest if text for cell already contains double quotes? – demo Dec 01 '14 at 13:55
  • Did you even try to search? Double quote will act as an escaped quote, [look here](http://stackoverflow.com/questions/12473480/how-should-i-escape-commas-and-speech-marks-in-csv-files-so-they-work-in-excel). – Askolein Dec 01 '14 at 13:57