c# how to download datagridview to Excel
There are several ways to download a DataGridView to Excel in C#. One approach is to use the Microsoft Office Interop Excel library. Here is an example code snippet:
using Microsoft.Office.Interop.Excel;
// create a new Excel application
var excelApp = new Application();
excelApp.Visible = false;
// create a new workbook
var workbook = excelApp.Workbooks.Add();
// get the active worksheet
var worksheet = (Worksheet)workbook.ActiveSheet;
// iterate through the DataGridView rows and columns
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
// set the cell value
worksheet.Cells[i + 1, j + 1] = dataGridView1.Rows[i].Cells[j].Value;
}
}
// save the workbook to a file
workbook.SaveAs("DataGridView.xlsx");
// close the workbook and Excel application
workbook.Close();
excelApp.Quit();
This code creates a new Excel application, adds a new workbook, and populates it with the data from the DataGridView. It then saves the workbook to a file and closes the Excel application. Note that the Microsoft Office Interop Excel library requires Microsoft Excel to be installed on the machine where the code is running
原文地址: https://www.cveoy.top/t/topic/dxEA 著作权归作者所有。请勿转载和采集!