Datagridview导出到Excel无法正常工作

我想问一下,我的出口到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,popup一个空白的excel工作簿,我想从我的数据网格视图导出的项目不在那里。 我是新来的C#应用​​程序。

问题再次出现在:

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

您不能使用Workbook接口将ActiveSheet分配给您必须使用应用程序接口的variables…

张:

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

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

“这个接口是由Visual Studio Tools for Office运行时实现的,不能在你的代码中实现,有关更多信息,请参见Visual Studio Tools for Office Runtime Overview。