How to export Excel data in WinForms?

You can use the Microsoft.Office.Interop.Excel library to export Excel data. Here is a simple example code demonstrating how to export data from WinForms to an Excel file.

using Excel = Microsoft.Office.Interop.Excel;

// ...

private void ExportToExcel()
{
    // 创建一个Excel应用程序对象
    Excel.Application excelApp = new Excel.Application();
    excelApp.Visible = true;

    // 添加一个工作簿
    Excel.Workbook workbook = excelApp.Workbooks.Add(Type.Missing);

    // 获取第一个工作表
    Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet;

    // 在Excel工作表中填充数据
    // 假设您有一个名为"dataGridView"的DataGridView控件
    for (int i = 0; i < dataGridView.Rows.Count; i++)
    {
        for (int j = 0; j < dataGridView.Columns.Count; j++)
        {
            worksheet.Cells[i + 1, j + 1] = dataGridView.Rows[i].Cells[j].Value.ToString();
        }
    }

    // 保存Excel文件
    workbook.SaveAs("D:\\data.xlsx");

    // 关闭Excel应用程序
    workbook.Close();
    excelApp.Quit();
}

Please note that you need to add a reference to the Microsoft.Office.Interop.Excel library in your project. You can do this by right-clicking on your project in Visual Studio, selecting “Add” > “Reference.” In the “Reference Manager,” search for and select “Microsoft.Office.Interop.Excel,” and then click the “OK” button.

This example exports data from a DataGridView control named “dataGridView” to an Excel file named “data.xlsx”. You can modify it according to your own needs. Make sure you have permission to save the file to the specified path.

bannerAds