c# - Excel 互操作 - 添加工作表并通过返回值更改名称
问题描述
我正在尝试Add
使用它的返回值更改通过该方法创建的工作表的名称。这是stackoverflow上的几个anwsers建议的。但它不起作用并给出带有错误代码的 COMException 0x800401A8
。其他两种方法工作正常。有人可以给我一个提示,为什么第一种方法不起作用?
编码:
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(fileInfo.FullName);
// Creates a new worksheet, chart, or macro sheet. The new worksheet becomes the active sheet.
var sheet = wb.Sheets.Add(Before: Type.Missing, After: wb.Sheets[wb.Sheets.Count], Count: 1, Type: XlSheetType.xlWorksheet);
try
{
((Worksheet)sheet).Name = "ASDF";
} catch(COMException e)
{
Trace.WriteLine($"Fail 1 - 0x{e.ErrorCode:X}");
}
try
{
((Worksheet)wb.ActiveSheet).Name = "ASDF";
} catch(COMException e)
{
Trace.WriteLine($"Fail 2 - 0x{e.ErrorCode:X}");
}
try
{
((Worksheet) wb.Sheets[wb.Sheets.Count]).Name = "ASDF";
} catch (COMException e)
{
Trace.WriteLine($"Fail 3 - 0x{e.ErrorCode:X}");
}
跟踪输出:
Fail 1 - 0x800401A8
详细异常:
threw an exception of type 'System.Runtime.InteropServices.COMException'
Data: {System.Collections.ListDictionaryInternal}
ErrorCode: -2147221080
HResult: -2147221080
HelpLink: null
InnerException: null
Message: "0x800401A8"
Source: "Testfall-Manager"
StackTrace: " at Microsoft.Office.Interop.Excel._Worksheet.set_Name(String RHS)"
TargetSite: {Void set_Name(System.String)}
解决方案
这是excel文件本身。上述方法适用于空的 excel 文件 (xlsx)
推荐阅读
- powerbi - 如何根据总值显示柱形图值
- json - 访问 Google 表格上的 API 响应
- pytorch - 直接更新优化器学习率
- regex - .htaccess:“RewriteRule ^ -”和“RewriteRule ^(.*)$ /$1”有什么区别?
- javascript - 如何为 chrome 创建 vpn 扩展
- php - 多个 WHERE 子查询性能
- bash - bash根据数组查找值替换字符串
- python - 未在 Python 中使用 for-loop 全局安装的模块(Google Colab)
- angular - 在ag grid community v22中重置infinitePageRowModel中的缓存
- javascript - 由于 translate3d 属性,SwiperJS 模板第一张卡片有偏移