What is the fastest way to export dataGridView rows to Excel or into an SQL Server database

后端 未结 6 651
醉话见心
醉话见心 2021-01-18 07:02

What is the fastest way to export DataGridView rows in the range of 460328 - 800328 to Excel or into an SQL Server database table with out using Microsoft office interop as

6条回答
  •  别那么骄傲
    2021-01-18 07:59

    One option would be to write data to a CSV file instead of an Excel file. Excel would have no problem reading it afterwards.

    If you're not familiar, in CSV (i.e. Comma Separated) files the fields are separated by commas and rows are separated by newlines (\n or \r\n).

    Something like (may not compile!):

    private void WriteData() {
        using (var file = System.IO.StreamWriter(@"C:\Path\To\File.csv")) {
            foreach (var row in dataGrid.Rows) {
                 foreach (var cell in row.Cells) {
                     // Note that if some cells contain commas, 
                     // you'd need to wrap them in quotes.
                     file.Write(cell.Value).Write(",");
                 }
            }
            file.Write("\n");
        }
    }
    

    For faster performance, it may also be a good idea collect a few hundred (or thousand) rows into a single string and then write it to a file, instead of writing cell-by-cell.

提交回复
热议问题