首页 文章

将数据DataGridView导出到Excel

提问于
浏览
0

我正在创建一个类,将数据从 DataGridView 导出到Excel文件 . 当我调用该方法时,我得到一个空的excel表 . 但是,当我在不使用类的情况下直接在代码中插入方法时,它确实有效 .

知道为什么这个课不起作用 .

class ExportToExcel
{
       public Microsoft.Office.Interop.Excel.Application ExcelApp =  new Microsoft.Office.Interop.Excel.Application();
       public Microsoft.Office.Interop.Excel._Workbook ExcelBook;
       public Microsoft.Office.Interop.Excel._Worksheet ExcelSheet;
       DataGridView dt = new DataGridView();

       public  DataGridView Dt { set { this.dt = value; } }


       public Microsoft.Office.Interop.Excel.Application exportToExcel(DataGridView dt)
        {
        int i = 0;
        int j = 0;



        ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1);
        ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet;
        //export header
        for (i = 1; i <= this.dt.Columns.Count; i++)
        {
            ExcelSheet.Cells[1, i] = this.dt.Columns[i - 1].HeaderText;
        }

        //export data
        for (i = 1; i <= this.dt.RowCount; i++)
        {
            for (j = 1; j <= dt.Columns.Count; j++)
            {
                ExcelSheet.Cells[i + 1, j] = dt.Rows[i - 1].Cells[j - 1].Value;
            }
        }


            ExcelApp.Visible = true;
            ExcelSheet = null;
            ExcelBook = null;
            ExcelApp = null;

         return ExcelApp;

    }
}

private void exportToExcel_Click(object sender, EventArgs e)
    {

        ExportToExcel ex = new ExportToExcel();
        ex.exportToExcel(dtReport2);
    }

1 回答

  • 3

    exportToExcel(DataGridView dt)

    看起来你的方法是引用this.dt(类变量)和本地版本的dt(作为参数传递给方法的那个) .

    根据您的代码 - dt的类版本永远不会被设置为任何东西 .

    我不确定您希望您的 class 如何工作,但您可能需要考虑设置dt而不是将另一个gridview传递到您的exportToExcel方法中 .

    private void exportToExcel_Click(object sender, EventArgs e)
    {
    
        ExportToExcel ex = new ExportToExcel();
        ex.dt = dtReport2; // set the public class variable here
        ex.exportToExcel(); // removed the datagrid from your parameter in the exportToExcel() method
    }
    

相关问题