我正在使用EPPlus将我的datagridview数据传输到excel文件,我的问题是进程正在吃内存,我错过了什么以释放已用内存?在外部看起来好几千行,但程序使用的内存上升,并不会在导出和保存到Excel后回落。现在,当我尝试导出一百万行时,内存不足。将datagridview数据传输到excel
这是我的代码,这个过程在后台工作上运行。
Using p = New ExcelPackage
Dim sheetnum As Integer = 2
Dim ws As ExcelWorksheet = CreateSheet(p, "report")
For Each dgcol As DataGridViewColumn In dg.Columns
ws.Cells(1, col).Value = dgcol.HeaderText
col += 1
Next
For Each rowx As DataGridViewRow In dg.Rows
For Each colx As DataGridViewColumn In dg.Columns
ws.Cells(row, colx.Index + 1).Value = dg.Rows(rowx.Index).Cells(colx.Index).Value
Next
row += 1
BackgroundWorker1.ReportProgress(CInt(100 * Integer.Parse(rowx.Index + 1)/dg.Rows.Count), CInt(100 * Integer.Parse(rowx.Index + 1)/dg.Rows.Count))
If row = 1048577 Then 'Check if max rows have been reached and create a new sheet
ws = CreateSheet(p, "report" & sheetnum)
sheetnum += 1
row = 2
col = 1
For Each dgcol As DataGridViewColumn In dg.Columns
ws.Cells(1, col).Value = dgcol.HeaderText
col += 1
Next
End If
Next
Dim bin() As Byte = p.GetAsByteArray()
File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & "report.xlsx", bin)
End Using
完成使用后,您需要处置['ExcelWorksheet'](https://epplus.codeplex.com/SourceControl/latest#EPPlus/ExcelWorksheet.cs)。 –
@RezaAghaei感谢您的建议,但没有奏效。 – crimson589
我不确定它是否解决了整个问题,但是如果您看一下执行'ExcelWorksheet'类的'Dispose'方法,您将看到代码释放了很多资源,可能代码的作者知道的更好比我们需要释放一些资源。 –