In my MVC project, users can select some products in the UI and download the related product information in Excel (.xlsx) format.
Our business requirements is, apart from few columns/cells the file should be read-only. I'm using EPPlus 4.0.4
to generate the Excel, and it's working great so far.
The issues I'm facing here is, the moment I make the worksheet protected, user cannot re-size the columns anymore (dragging the header to change column width). So, texts in some columns are not visible completely. To fix that, I made them AutoFit (## in code below). So, texts are visible now. But still, user cannot change the column widths which they should be able to.
So my questions is, can I make the cells/columns read-only but make them re-sizable like normal Excel?
My code below
//using OfficeOpenXml;
//using OfficeOpenXml.Style;
private void ProtectExcel(ExcelWorksheet ws, int columnCount)
{
ws.Protection.AllowSort = true;
ws.Protection.AllowSelectUnlockedCells = true;
ws.Protection.AllowAutoFilter = true;
for (int i = 1; i <= columnCount; i++)
{
ws.Column(i).Style.Locked = true; //making read-only
ws.Column(i).AutoFit(); //## showing all text
}
ws.Protection.IsProtected = true; //making the sheet protected
}
There are many properties on the ws.Protection
property to specify what will be protected. One is AllowFormatColumns
, so:
ws.Protection.AllowFormatColumns = true;