繁体   English   中英

如何使用 C# 从 DataGridView 创建具有多个工作表的 excel 文件

[英]How to create excel file with multiple sheets from DataGridView using C#

我想将 DataGridViews 数据导出到 Excel 文件中。 我想制作 3 张表并将数据导出到这些表中。 一张工作表没有问题。 但是,当我想制作更多工作表并单击按钮时,会出现以下错误消息。

Debugger:Exception Intercepted: button1_Click, Form2.cs line 34 一个异常被截获并且调用堆栈展开到从发生异常的用户代码调用之前的点。 在调试器选项中选择了“Unwind the call stack on unhandled exceptions”。 时间:2020 年 5 月 20 日晚上 11:11:53 主题:[17068]

这是按钮单击事件。

private void button1_Click(object sender, EventArgs e)
    {
        // creating Excel Application  
        Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
        // creating new WorkBook within Excel application  
        Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
        // creating new Excelsheet in workbook  
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
        // see the excel sheet behind the program  
        app.Visible = true;
        // get the reference of first sheet. By default its name is Sheet1.  
        // store its reference to worksheet  
        for (int x = 0; x < 3; x++)
        {
            worksheet = workbook.Sheets["Sheet"+x+""];
            worksheet = workbook.ActiveSheet;
            // changing the name of active sheet  
            worksheet.Name = "Exported from gridview";
            // storing header part in Excel  
            for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
            {
                worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }
            // storing Each row and column value to excel sheet  
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value;
                }
            }
        }

        // save the application  
        workbook.SaveAs("c:\\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        // Exit from the application  
        //app.Quit();  
    }

解决方案:

代替

工作簿.Sheets.Add();

工作表 = 工作簿.Sheets["工作表"+x+""];

并将计数器添加到工作表名称

worksheet.Name = "从gridview导出"+x+"";

资助答案。 只需更换

工作簿.Sheets.Add();

工作表 = 工作簿.Sheets["工作表"+x+""];

并将计数器添加到工作表名称

worksheet.Name = "从gridview导出"+x+"";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM