【发布时间】:2014-12-23 01:07:05
【问题描述】:
我想问一下为什么我的导出到 excel 代码不起作用。我在工具条菜单中单击了此代码。
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# 应用程序的新手。
【问题讨论】:
-
摆脱那个 try/catch。它是在向您隐藏问题,而不是解决问题您还应该摆脱所有
GC的东西。如果您是新手,那么您可能根本不知道该代码在做什么。 -
@JohnSaunders 我已经删除了 try/catch,没有错误但弹出的工作簿仍然是空白的。
-
好。现在你知道没有没有错误了。以前,可能会出现错误,但您不会知道。
-
@JohnSaunders 你有解决这个问题的办法吗?我不明白,为什么我的数据网格视图上的数据没有出现在加载的工作簿上。
-
我的解决方案是通过代码进行调试。例如,我会确保两个循环都真正执行。我会确定我将哪些数据放入单元格中。我还质疑为什么您要在查看工作簿中是否有数据之前摆脱工作簿。如果你除了像我问的那样摆脱
GC代码之外,还摆脱oSheet = null会发生什么?
标签: c# excel winforms datagridview