在重构机房,完成EXCEL导出功能时出现异常。
当运行到导出EXCEL的语句:
<span style="font-family:KaiTi_GB2312;font-size:24px;">xlApp.Cells(rowindex, colindex) = row(col.ColumnName)</span>时,显示异常:
对此,特查找原因与解决方法,在此与大家分享,也请高手多指教呀!
原因:程序在运行调用传递地址时起冲突,导致出现此异常。
解决方法:将源代码替换成一下代码即可。
<span style="font-family:KaiTi_GB2312;font-size:24px;">Dim MyExcel As NewMicrosoft.Office.Interop.Excel.Application() MyExcel.Application.Workbooks.Add(True) MyExcel.Visible = True '将datagridview中的字段名导出 Dim m As Integer For m = 0 To DataGridView1.ColumnCount - 1 MyExcel.Cells(1, m + 1) = Me.DataGridView1.Columns(m).HeaderText Next m '往excel表里添加数据 Dim i As Integer For i = 0 To DataGridView1.RowCount - 1 Dim j As Integer For j = 0 To DataGridView1.ColumnCount - 1 If Me.DataGridView1(j, i).ValueIs System.DBNull.Value Then MyExcel.Cells(i + 2, j + 1)= "" Else MyExcel.Cells(i + 2, j + 1)= DataGridView1(j, i).Value.ToString End If Next j Next i</span>
原文地址:http://blog.csdn.net/zygyl/article/details/44487657