MarkPflug / Sylvan.Data.Excel

The fastest .NET library for reading Excel data files.
MIT License
241 stars 29 forks source link

SAVE THE DATAGRIDVIEW CONTENTS AS EXCEL #193

Open FreeVB opened 3 days ago

FreeVB commented 3 days ago

At present, only DbDataReader can be saved as excel, but not datatable or datagridview?

FreeVB commented 3 days ago

I found a solution: first convert datagridview to datatable, then new DataTableReader(dataTable)

private void button2_Click(object sender, EventArgs e)
{
    string filePath = @"file.xlsx";
    using ExcelDataWriter edw = ExcelDataWriter.Create(filePath);
    edw.Write(DataGridView2DbDataReader(dataGridView1));
}

static DbDataReader DataGridView2DbDataReader(DataGridView Dgv)
{
    DataTable dt = new();
    foreach (DataGridViewColumn column in Dgv.Columns)
    {
        dt.Columns.Add(column.HeaderText, column.ValueType);
    }
    foreach (DataGridViewRow row in Dgv.Rows)
    {
        DataRow dr = dt.NewRow();
        foreach (DataGridViewCell cell in row.Cells)
        {
            dr[cell.ColumnIndex] = cell.Value;
        }
        dt.Rows.Add(dr);
    }
    return new DataTableReader(dt);
}