数据网格视图导出到 excel 不起作用


我想

问一下为什么我的导出到 excel 代码不起作用。我的工具tripmenu单击中有此代码。

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, "", "");
}

我在此类中有此代码,用于将我的数据网格视图项导出到 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# 应用程序的新手。

问题再次出在:

获取活动工作表 oSheet = (Excel.Worksheet(oWB.ActiveSheet; oSheet.Name ="附件";

您不能使用工作簿界面将活动工作表分配给您必须使用应用程序界面的变量...

将其改为:

获取活动工作表 oSheet = (Excel.Worksheet(oXL.ActiveSheet; oSheet.Name ="附件";

进一步说明:MSDN 提供了以下有关工作簿接口的说明。

"此接口由Visual Studio Tools for Office运行时实现。它不应在代码中实现。有关详细信息,请参阅 Visual Studio Tools for Office Runtime 概述。

最新更新