简体   繁体   中英

How to add new sheet in an existing workbook?

I'm trying to create a new sheet using c# using the code below. My excel file has already 2 sheets and the problem is adding a third one. However the program crashes in the line where I create the 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.

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); 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.

All parameters are optional; may be you should simply pass Type.Missing instead of 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.

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