I'm transferring my datagridview data to an excel file using EPPlus, my problem is the process is eating memory, what am I missing to free up the used memory? on the outside it seems fine with a few thousand rows but the memory used by the program rises and doesn't go back down after exporting and saving to excel. Now when I try to export a million rows I run out of memory.
Here's my code, this process runs on a background worker.
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