2017-02-22 80 views
-1

我正在使用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 
+0

完成使用后,您需要处置['ExcelWorksheet'](https://epplus.codeplex.com/SourceControl/latest#EPPlus/ExcelWorksheet.cs)。 –

+0

@RezaAghaei感谢您的建议,但没有奏效。 – crimson589

+0

我不确定它是否解决了整个问题,但是如果您看一下执行'ExcelWorksheet'类的'Dispose'方法,您将看到代码释放了很多资源,可能代码的作者知道的更好比我们需要释放一些资源。 –

回答

0

,因为它是在using块包围,所述ExcelPackage对象被适当处理。你说你还在评论中处理了ExcelWorksheet这个对象,但是没有成功。

但是,我认为你是不处置,你写在代码的最后一行(End Using之前)以文件的字节数组

尝试。希望能帮助到你。

+0

字节 – crimson589

+0

没有'.dispose'请阅读:http://stackoverflow.com/questions/13033684/how-do-i-properly-dispose-the-byte-array-used-in-the-class - 基本上,你可以调用垃圾收集器并要求收集 –

相关问题