ClosedXML 内存泄漏或OutOfMemory错误的原因

来源:互联网 发布:淘宝收藏 猪八戒网 编辑:程序博客网 时间:2024/04/30 22:04

上篇文章简单介绍了CloseXML使用,发现非常耗内存,今天解决了不是耗内存而是内存泄漏知道内存用光提出错误为止。

一定要看ClosedXML的帮助 https://github.com/ClosedXML/ClosedXML/wiki

收获1:

新创建的xlsx文件,必须设置Workbook的属性,否则出现错误。

using(var wb = new XLWorkbook())

{

//不给下面的属性赋值,保存的时候出现错误

wb.Properties.Author = "theAuthor";
wb.Properties.Title = "theTitle";
wb.Properties.Subject = "theSubject";
wb.Properties.Category = "theCategory";
wb.Properties.Keywords = "theKeywords";
wb.Properties.Comments = "theComments";
wb.Properties.Status = "theStatus";
wb.Properties.LastModifiedBy = "theLastModifiedBy";
wb.Properties.Company = "theCompany";
wb.Properties.Manager = "theManager";

using(var ws = wb.Worksheets.Add("sheet1"))

{


收获2:

添加行的时候的释放,官网推荐下面的方法

using(var row = ws.Row(1)) //此处不释放会造成内存泄漏,这就是上篇文章中使用出现outofmemory错误的主要原因

{

row.Cell(1).Value = "xxxx";

...

}


收获3:

即使读xlsx文件的时候行同样需要释放

 var rows = ws.RowsUsed();
 foreach (var row in rows)
  {

....

row.Dispose();//没有此处代码会内存泄漏,有比没有内存会消耗的少

}


收获4:

使用Lambda表达式进行过滤

比如:单列数据过滤

//取单列,firstcellcolumn和lastcellcolumn相同即可

var range = wb.Worksheets.First().Range(firstcellrow, firstcellcolumn, lastcellrow, lastcellcolumn);//也可以使用A2:B111,这种需要将A2:B111转换为行列的方式!

//过滤值为xxxx的单元格

foreach(var cell in range.Cells(c =>

{

string s;

s = c.GetString().Trim();

return string.Equals(s, "xxxx");

}

)

{

//cell  就是值为xxxx的单元格

cell.CellRight(5);//从当前单元格跳转到右面第5个单元格

....

}


经过上面的优化,

6153条记录的文件在二个文件记录数:1906 2042中遍历查询,耗时1分钟左右。没使用定时器。不精确而且是开发环境下调试环境下的时间。已经满意了!!!



0 0
原创粉丝点击