在C# Windows窗体中将DataGridView数据导出到Excel文件

f0ofjuux  于 2023-05-23  发布在  C#
关注(0)|答案(1)|浏览(203)

Excel文件保存到本地驱动器在C# Windows形式
我有一个数据网格视图。我想以excel格式下载或保存到本地驱动器。excel文件与行数据或没有行只有标题文本名称时,点击按钮。

pobjuy32

pobjuy321#

//create a data table//

                DataTable dt = new DataTable();

                //Adding the Columns only for header text
                dt.Columns.Add("ITEM");
                dt.Columns.Add("ODERQTY");
                dt.Columns.Add("EXPDAT");
                dt.Columns.Add("STK");

 //Adding the Rows if you want. Otherwise ignore this foreach loop//
   
 foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        dt.Rows.Add();
        foreach (DataGridViewCell cell in row.Cells)
        {
            dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
        }
    }

//save or export part/

        SaveFileDialog saveDialog = new SaveFileDialog();
                DialogResult result = saveDialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    String fileName = saveDialog.FileName;
                    //your code to save the file;
                    using (XLWorkbook wb = new XLWorkbook())
                    {
                        wb.Worksheets.Add(dt, "sampleOrder");
                        wb.SaveAs(fileName);
                        MessageBox.Show("Excel Downloaded.");
                    }
                }

相关问题