how to get EPPlus OpenXML row count (c#)

我是研究僧i 提交于 2019-12-08 14:56:18

问题


I searched for it and found the link C# EPPlus OpenXML count rows

int iRowCount = currentWorksheet.Dimension.End.Row - currentWorksheet.Dimension.Start.Row;

But this gives a value of 4721 as count. It is giving the whole row count, how can I get row count of rows which has value. Something like UsedRange.


回答1:


You can get the count by workBook.Worksheets.Count




回答2:


Actual Answer to return the number of Rows and Columns of the UsedRange (the dimention) of a sheet is...

int iColCnt = Worksheet.Dimension.End.Column
int iRowCnt = Worksheet.Dimension.End.Row

But you need to test if Worksheet.Dimension is null because for new worksheets or empty worksheets the Dimension property will be null.




回答3:


Empty cells in a worksheet may still contain formatting causing them to be counted in the sheet Dimension:

Empty cells can be cleared using the steps here: http://office.microsoft.com/en-au/excel-help/locate-and-reset-the-last-cell-on-a-worksheet-HA010218871.aspx

I wrote this function to get the last row that contains text:

int GetLastUsedRow(ExcelWorksheet sheet) {
    var row = sheet.Dimension.End.Row;
    while(row >= 1) {
        var range = sheet.Cells[row, 1, row, sheet.Dimension.End.Column];
        if(range.Any(c => !string.IsNullOrEmpty(c.Text))) {
            break;
        }
        row--;
    }
    return row;
}



回答4:


There is a way to get the cells that don't have no value using the Where method. We can use it to find the very last cell (and its row in this case) from a worksheet, or a range.

int lastRow = sheet.Cells.Where(cell => !cell.Value.ToString().Equals("")).Last().End.Row;

About the Where method : https://msdn.microsoft.com/en-us/library/bb534803(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1




回答5:


Another way to do it.

var lastRow = sheet.Cells.Where(cell => !string.IsNullOrEmpty(cell.Value?.ToString() ?? string.Empty)).LastOrDefault().End.Row;



来源:https://stackoverflow.com/questions/8400315/how-to-get-epplus-openxml-row-count-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!