简体   繁体   English

如何在ExcelPlus C#中将Excel列设置为只读但可调整大小?

[英]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. 在我的MVC项目中,用户可以在UI中选择一些产品,并以Excel(.xlsx)格式下载相关产品信息。

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. 我正在使用EPPlus 4.0.4生成Excel,并且到目前为止效果很好。

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). 为了解决这个问题,我将它们设置为AutoFit(以下代码中的##)。 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? 所以我的问题是,我可以将单元格/列设置为只读,但可以像普通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. ws.Protection属性上有许多属性来指定要保护的内容。 One is AllowFormatColumns , so: 一种是AllowFormatColumns ,所以:

ws.Protection.AllowFormatColumns = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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