Exporting datagridview to csv file

后端 未结 8 1805
南方客
南方客 2020-11-29 10:11

I\'m working on a application which will export my DataGridView called scannerDataGridView to a csv file.

Found some example code to do this, but can\'t get it worki

相关标签:
8条回答
  • 2020-11-29 10:41

    LINQ FTW!

    var sb = new StringBuilder();
    
    var headers = dataGridView1.Columns.Cast<DataGridViewColumn>();
    sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));
    
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        var cells = row.Cells.Cast<DataGridViewCell>();
        sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
    }
    

    And indeed, c.Value.ToString() will throw on null value, while c.Value will correctly convert to an empty string.

    0 讨论(0)
  • 2020-11-29 10:42

    A little known feature of the DataGridView is the ability to programmatically select some or all of the DataGridCells, and send them to a DataObject using the method DataGridView.GetClipboardContent(). Whats the advantage of this then?

    A DataObject doesn't just store an object, but rather the representation of that object in various different formats. This is how the Clipboard is able to work its magic; it has various formats stored and different controls/classes can specify which format they wish to accept. In this case, the DataGridView will store the selected cells in the DataObject as a tab-delimited text format, a CSV format, or as HTML (*).

    The contents of the DataObject can be retrieved by calling the DataObject.GetData() or DataObject.GetText() methods and specifying a predefined data format enum. In this case, we want the format to be TextDataFormat.CommaSeparatedValue for CSV, then we can just write that result to a file using System.IO.File class.

    (*) Actually, what it returns is not, strictly speaking, HTML. This format will also contain a data header that you were not expecting. While the header does contain the starting position of the HTML, I just discard anything above the HTML tag like myString.Substring(IndexOf("<HTML>"));.

    Observe the following code:

    void SaveDataGridViewToCSV(string filename)
    {        
        // Choose whether to write header. Use EnableWithoutHeaderText instead to omit header.
        dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
        // Select all the cells
        dataGridView1.SelectAll();
        // Copy selected cells to DataObject
        DataObject dataObject = dataGridView1.GetClipboardContent();
        // Get the text of the DataObject, and serialize it to a file
        File.WriteAllText(filename, dataObject.GetText(TextDataFormat.CommaSeparatedValue));
    }
    

    Now, isn't that better? Why re-invent the wheel?

    Hope this helps...

    0 讨论(0)
  • 2020-11-29 10:50

    Found the problem, the coding was fine but i had an empty cell that gave the problem.

    0 讨论(0)
  • 2020-11-29 10:50

    I think this is the correct for your SaveToCSV function : ( otherwise Null ...)

     for (int i = 0; i < columnCount; i++)
    

    Not :

     for (int i = 1; (i - 1) < DGV.RowCount; i++)
    
    0 讨论(0)
  • 2020-11-29 10:51

    The line "csvFileWriter.WriteLine(dataFromGrid);" should be moved down one line below the closing bracket, else you'll get a lot of repeating results:

    for (int i = 1; i <= countColumn; i++)
    {
    dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
    }
    csvFileWriter.WriteLine(dataFromGrid);
    
    0 讨论(0)
  • 2020-11-29 10:53

    Your code was almost there... But I made the following corrections and it works great. Thanks for the post.

    Error:

    string[] output = new string[dgvLista_Apl_Geral.RowCount + 1];
    

    Correction:

    string[] output = new string[DGV.RowCount + 1];
    

    Error:

    System.IO.File.WriteAllLines(filename, output, System.Text.Encoding.UTF8);
    

    Correction:

    System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
    
    0 讨论(0)
提交回复
热议问题