c# - Excel 工作表只读和 C#

标签 c# excel

我正在尝试通过 C# 代码编辑 Excel 工作表,但 Excel 工作表给我一个错误,指出只读

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

这是尝试访问工作表的代码。 代码:

//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;

在属性中,Excel 工作表不是只读的,当我打开它进行编辑时,它不会提示我“此文档是只读的,想要启用编辑”。我该如何解决这个问题,Visual Studio 不会让我编译。

这是 Office365 中的 Excel。

最佳答案

您想使用.Value而不是.Text

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

如果您检查documentation您可以看到文本只读

此外,如果您检查 documentation您可以看到 Value 不是只读。

编辑

您可能还需要将 Open 参数更改为:

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

关于c# - Excel 工作表只读和 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45549557/

相关文章:

c# - 如何从 ORed 标志中检索返回值

Excel:比较不同 Excel 工作簿中的数据时避免使用复杂的公式

excel - 查找最先出现的数字的行索引

c# - 什么时候应该使用存储在数据库中的枚举以及什么时候在代码中使用枚举?

c# - 如何解析 xml 并读取其值

c# - 双击数据网格的问题

Java 关闭 Hook 并写入 Excel 工作表

excel - 在二维数组的每一行中,匹配一个值,以生成发生匹配的列位置列表

xml - 导出到 Excel - 中间文件格式?

c# - 如何将 where 子句与 IQueryable<dynamic> 一起使用