简体   繁体   中英

Excel sheet read only and C#

I'm trying to edit an Excel Sheet through C# code but the Excel sheet is giving me an error saying read only

CS0200 Property or indexer 'Range.Text' cannot be assigned to -- it is read only

This is the code that is trying to access the sheet. Code:

//Load workbook
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"S:\Utils\documents\ServerManager\serverlist.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;

xlWorksheet.Range["D2"].Text = "Kelly Cooper";
xlWorksheet.Range["D2"].Style.Font.FontName = "Arial Narrow";
xlWorksheet.Range["D2"].Style.Font.Color = Color.DarkBlue;

In the properties the Excel sheet is not read only and when I open it to edit it does not prompt me with the "This document is read only, want to enable editing." How can I go around this, Visual Studio won't let me compile because of it.

This is Excel in Office365.

You want to use .Value instead of .Text .

xlWorksheet.Range["D2"].Value = "Kelly Cooper";
xlWorksheet.Range["D2"].Style.Font.FontName = "Arial Narrow";
xlWorksheet.Range["D2"].Style.Font.Color = Color.DarkBlue;

If you check the documentation you can see that Text is read-only .

Also, if you check the documentation you can see that Value is not read-only.

EDIT

You also might have to change your Open parameters to:

Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Filename: "path/to/file", ReadOnly: false);

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