如何使用具有相同名称的另一个工作表替换Excel工作簿中的工作表 [英] How do I replace a worksheet in an excel workbook with another worksheet having same name

查看:568
本文介绍了如何使用具有相同名称的另一个工作表替换Excel工作簿中的工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个应用程序,如果工作表名称不存在,则需要我在现有工作簿中创建Excel工作表,如果已存在则替换它。

我已经尝试使用下面的代码,但我得到一个错误,说对象引用未设置为对象的实例。请问有什么问题吗?

这是代码。

I'm working on an application which requires me to create an excel worksheet in an existing workbook if the worksheet name doesn't exist and to replace it if it already exists.
I've tried using the code below but I get an error which says "Object reference not set to instance of an object". Please any ideas what is going wrong ?
This is the code.

foreach (Worksheet wsheet in entire_workbook.Worksheets)
if (wsheet.Name.Equals(sheet_name))
{
    Excel.DisplayAlerts = false;
    wsheet.Delete();
    entire_workbook.Save();
    Excel.DisplayAlerts = true;
    break;
}
weekly_worksheet = (Worksheet)weekly_workbook.Sheets[1];
//entire_worksheet = (Worksheet)entire_workbook.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
weekly_worksheet.Copy(entire_worksheet, Missing.Value); //error occurs here
entire_workbook.Save();
weekly_workbook.Save();
entire_workbook.Close(false, Type.Missing, Type.Missing);

推荐答案

循环使用低效的工作表集合。而是使用与此类似的东西:

Looping through the collection of worksheets in inefficient. Rather use something similar to this:
try
{
Worksheet wsh = YourWorkbook.Worksheets["WorksheetName"];
wsh.Delete();
}
catch (...)
{
   //do not inform about errors ;)
}
//now you can add worksheet with the same name ;)





注意:未经测试!



Note: Not tested!


这篇关于如何使用具有相同名称的另一个工作表替换Excel工作簿中的工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆