首页 文章

Datagridview导出到excel不起作用

提问于
浏览
1

我想问一下我的excel代码导出是怎么回事 . 我在我的toolstripmenu点击中有这个代码 .

private void excelFileToolStripMenuItem_Click(object sender, EventArgs e)
{
    string[] arrays = new string[this.dgvResult.Columns.Count];
    int icol = 0;

    foreach (DataGridViewColumn gridColum in this.dgvResult.Columns)
    {
        //for (irow = 0; irow <= this.dgvResult.Columns.Count - 1; irow++)
        //{

        arrays[icol] = this.dgvResult.Columns[icol].Name;
        icol++;
        // }
    }
    SystemUtil.ExportToExel_DG(dgvResult, arrays, "", "");
}

我在这个类中有这个代码来将我的datagridview项导出到excel中

public void ExportToExel_DG(DataGridView dg, string[] arrays,string sTitle,string sRundate)
{
    try
    {
        Excel.Application oXL;
        Excel.Workbook oWB;
        Excel.Worksheet oSheet;
        //Excel.Range oRange;

        oXL = new Excel.Application();
        // Set some properties 
        oXL.Visible = true;
        oXL.DisplayAlerts = false;

        // Get a new workbook. 
        oWB = oXL.Workbooks.Add(Missing.Value);

        // Get the active sheet 
        oSheet = (Excel.Worksheet)oWB.ActiveSheet;
        oSheet.Name = "Attachment";


        //Title
        //oSheet.Cells[1, 2] = "Corporate Name:" + sTitle;
        //oSheet.Cells[2, 2] = "Utilization Reports";
        //oSheet.Cells[3, 2] = "Run Date: "  + sRundate;


        int rowCount = 1;
        int RecNo = 1;
        foreach (DataGridViewRow dgr in dg.Rows)
        {
            int iCell = 2;
            rowCount += 1;

            for (int i = 1; i <= dg.ColumnCount; i++)
            {
                if (rowCount == 1)
                {
                    oSheet.Cells[1, 1] = "Record No.";
                    oSheet.Cells[1, iCell] = arrays[i - 1];// dt.Columns[i - 1].ColumnName;
                }                        
                oSheet.Cells[rowCount, 1] = RecNo;
                oSheet.Cells[rowCount, iCell] = dgr.Cells[i - 1].Value.ToString();

                iCell++;
            }
            RecNo++;
        }

        oSheet.Cells[rowCount + 1, 2] = "TOTAL";


        oSheet.Columns.AutoFit();
        oSheet = null;

        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }
    catch
    {
    }
}

每次单击工具条菜单导出到Excel时,都会弹出一个空白的Excel工作簿,我想从数据网格视图中导出的项目不在那里 . 我是制作c#应用程序的新手 .

1 回答

  • 0

    问题再次出现在:

    //获取活动工作表oSheet =(Excel.Worksheet)oWB.ActiveSheet; oSheet.Name =“附件”;

    您无法使用工作簿界面将ActiveSheet分配给必须使用应用程序界面的变量...

    张它:

    //获取活动工作表oSheet =(Excel.Worksheet)oXL.ActiveSheet; oSheet.Name =“附件”;

    进一步说明:MSDN提供了有关工作簿界面的以下注释....

    “此接口由Visual Studio Tools for Office运行时实现 . 它不适用于您的代码 . 有关详细信息,请参阅用于Office运行时概述的Visual Studio工具 . ”

相关问题