简体   繁体   English

如何在现有工作簿中添加新工作表?

[英]How to add new sheet in an existing workbook?

I'm trying to create a new sheet using c# using the code below. 我正在尝试使用c#使用以下代码创建一个新工作表。 My excel file has already 2 sheets and the problem is adding a third one. 我的Excel文件已经有2张纸,问题是添加了第三张纸。 However the program crashes in the line where I create the var newS . 但是,程序在我创建var newS的行中崩溃。 Can someone please explain why? 有人可以解释为什么吗?

I know for sure that the problem is not before the creation of newS because I've been debugging the code and it works perfectly fine without the last 2 lines. 我肯定知道问题不是在创建newS之前发生的,因为我一直在调试代码,并且在没有最后两行的情况下它可以很好地工作。

wbs= excel.Workbooks;
wb=wbs.Open(Path.Combine(App.Domain.BaseDiretory, template_path, template_filename)) 

Excel.Sheets shs=wb.Sheets;

Excel.Worksheet sh=shs[1] as Excel.Worksheet;
//code not relevant between these lines
Marshall.ReleaseComObject(sh);

Excel.Worksheet sh=shs[2] as Excel.Worksheet;
//code not relevant between these lines
Marshall.ReleaseComObject(sh);

var newS=(Excel.Worksheet)shs.Add(shs[3], Type.missing, Type.missing, Type.missing);

newS.name="1";

The shs.Add(shs[3], Type.missing, Type.missing, Type.missing); shs.Add(shs[3], Type.missing, Type.missing, Type.missing); does not look a valid call as you said you have two sheets in your workbook. 您说您的工作簿中有两张纸,因此该电话看起来无效。 You are attempting to add new sheet before third one which does not exist. 您正在尝试在不存在的第三个表之前添加新表。 Refer the documentation . 请参阅文档

Before - Optional - Variant - An object that specifies the sheet before which the new sheet is added. Before -可选-变形-一个对象,该对象指定在其之前添加新图纸的图纸。

All parameters are optional; 所有参数都是可选的; may be you should simply pass Type.Missing instead of shs[3] . 可能是您应该只传递Type.Missing而不是shs[3] New sheet will be added before the active sheet. 新工作表将添加到活动工作表之前。

If Before and After are both omitted, the new sheet is inserted before the active sheet. 如果同时省略了“之前”和“之后”,则将新工作表插入到活动工作表之前。

Alternatively, replace the call to represent the sheet that exists. 或者,替换该调用以表示存在的工作表。

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

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