EPPlus获得Excel的行数和列数

时间:2018-12-13 20:50:12

标签: c# epplus

我有一个Excel文件,其中包含5列5行。

我正在使用EPPlus(.net核心c#)来解析文件的内容。

我有以下代码来计算行和列,然后解析此excel文件的内容。

using (ExcelPackage package = new ExcelPackage(stream))
{    
    ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
    int rowCount = worksheet.Dimension.End.Row;
    int colCount = worksheet.Dimension.End.Column;

    for (int row = 1; row <= rowCount; row++)
    {
        for (int col = 1; col <= colCount; col++)
        {
            //Parse here
        }
    }
}

如前所述,具有5行5列数据可以正常工作。

如果我更新并保存相同的文件,然后删除说3行3列。

现在,如果我再次读取此文件,它仍然显示5列和行。不确定是否还有另一种读取实际行和列的方法?

我在这里想念什么吗?

1 个答案:

答案 0 :(得分:0)

尝试一下

    using (ExcelPackage package = new ExcelPackage(stream))
    {    
        string directoryServerPath = // your file saving path in server;

        if (!Directory.Exists(directoryServerPath))
          Directory.CreateDirectory(directoryServerPath);                     

        System.IO.DirectoryInfo directoryFiles = new DirectoryInfo(directoryServerPath);
        foreach (FileInfo file in directoryFiles.GetFiles())
        {
         file.IsReadOnly = false;
         file.Delete();
        }

        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int rowCount = worksheet.Dimension.Rows;
        int colCount = worksheet.Dimension.Columns;

        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                //Parse here
            }
        }

       package.SaveAs(new System.IO.FileInfo(directoryServerPath + fileName));
                    System.IO.File.SetAttributes(directoryServerPath + fileName, FileAttributes.ReadOnly);
    }