EPPlusSoftware / EPPlus

EPPlus-Excel spreadsheets for .NET
https://epplussoftware.com
Other
1.82k stars 278 forks source link

Open Excel file read only #1667

Closed rdhasse closed 2 weeks ago

rdhasse commented 2 weeks ago

Hello,

Is it possible to support opening an Excel file in read only mode when another user has it open in write mode?

With Excel, this situation will prompt the read only user that the file is locked and still allows them to open it in read only mode to view the content.

We would like to do the same with EPPlus by specifying read only mode such that our C# app can still read the file content.

Thanks,

Randall

swmal commented 2 weeks ago

Closing this issue since the corresponding support ticket was resolved. Proposed solution:

Extension method

using OfficeOpenXml;
using System.IO;

namespace OfficeOpenXmlExtensions
{
  public enum FileOpenResult
  {
    CanWrite,
    CanOpenReadOnly
  }

  public static class ExcelPackageExtensions
  {
    public static ExcelPackage OpenAndCheckLocked(this ExcelPackage package, string filePath, out FileOpenResult result)
    {
      result = FileOpenResult.CanWrite;
      try
      {
        var s = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
        package.Load(s);
      }
      catch(IOException ex)
      {
        var s = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        package.Load(s);
        result = FileOpenResult.CanOpenReadOnly;
      }
      return package;
    }
  }
}

Usage

using OfficeOpenXml;
using OfficeOpenXmlExtensions;

ExcelPackage.LicenseContext = LicenseContext.Commercial;

var path = @"c:\Temp\MyExcelFile.xlsx";

using var package = new ExcelPackage();
package.OpenAndCheckLocked(path, out FileOpenResult result);
if(result == FileOpenResult.CanWrite)
{
  package.Save();
}