EPPlus获得excel行和列数

问题描述 投票:0回答:1

我有一个excel文件,说5列5行。

我使用EPPlus(.net core 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列和行。不确定是否有其他方法可以读取实际的行和列?

我在这里错过了一些东西。

c# epplus
1个回答
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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.