如何在 Excel 电子表格上从 C# 更改工作表名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1829044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I Change the Sheet Name from C# on an Excel Spreadsheet
提问by Steve Goedker
I have a C# application where I am creating numerous Excel Files from Data in a Database. This part is working fine. However, my user asked if the sheet tab could be modified to reflect a field from the database. This sounds simple, however, when I try to reset the name, it tells me that it is read only and cannot be set. I have tried the following and it has not worked:
我有一个 C# 应用程序,我正在从数据库中的数据创建大量 Excel 文件。这部分工作正常。但是,我的用户询问是否可以修改工作表选项卡以反映数据库中的字段。这听起来很简单,但是,当我尝试重置名称时,它告诉我它是只读的,无法设置。我尝试了以下方法,但没有奏效:
xlApp.Sheets[0].Range["A1"].Value = "NewTabName";
ALSO TRIED:
还尝试过:
xlApp.Name = "NewTabName";
I did a google search and saw some other approaches which did not work for me as well. And a few responses indicated that it is readonly and could not be done.
我做了一个谷歌搜索,看到了一些对我也不起作用的其他方法。并且一些回复表明它是只读的,无法完成。
This seems like something that should be simple. How can I do it.
这看起来应该很简单。我该怎么做。
采纳答案by mikemurf22
You need to get access to the actual worksheet. Try something like:
您需要访问实际工作表。尝试类似:
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Worksheet)xlApp.Worksheets["Sheet1"];
worksheet.Name = “NewTabName”;