简体   繁体   中英

How to make Excel columns read-only but re-sizable in EPPlus C# ?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM