如何将Excel工作表从一个工作簿复制到另一个工作簿,相关的C#代码保持不变 [英] How to copy an Excel Worksheet from one workbook to another workbook with the associated C# code intact

查看:83
本文介绍了如何将Excel工作表从一个工作簿复制到另一个工作簿,相关的C#代码保持不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过将工作表模板复制到新工作簿中来使用主工作簿中的工作表模板。我已经为工作表模板(sheet1.cs)中的几个文档级事件提供了代码,这些事件需要在将
复制到新工作簿时遵循工作表。将模板Worksheet复制到新工作簿的代码功能齐全,但是当在新工作簿中打开工作表时,事件不起作用(它们在主工作簿中完全正常工作)。

I am trying to use a Worksheet template from a master Workbook by copying the Worksheet template into a new Workbook. I have provided code for several document level events within the Worksheet template (sheet1.cs) that need to follow the Worksheet when it is copied into the new Workbook. The code to copy the template Worksheet into the new Workbook is fully functional, but when the Worksheet is opened in the new Workbook, the events do not work (they are fully functional in the master Workbook).

我正在使用Visual Studio 2017 Professional和Excel 2016。

I am using Visual Studio 2017 Professional and Excel 2016.

有没有办法让C#代码(sheet1.cs代码)跟随工作表到新工作簿?

Is there a way to get the C# code (sheet1.cs code) to follow the Worksheet to the new Workbook?

推荐答案

Hi Phil,

Hi Phil,

Excel工作表有两种复制方式:复制同一文件和不同文件之间的复制。

There are two types of replication for Excel worksheets: Copying within the same document and copying between different documents.

1。使用Worksheet.copyfrom()方法将工作表复制到同一Excel文件中的另一个工作表:

1. Use the Worksheet.copyfrom() method to copy a worksheet to another worksheet in the same Excel file:

//Load Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile("DoughnutChart.xlsx");
//Get sheet1
Worksheet sheet1 = workbook.Worksheets[0];
//Add new Worksheet
Worksheet sheet2 = workbook.Worksheets.Add("Copy");
//Copy
sheet2.CopyFrom(sheet1);
//Save file
workbook.SaveToFile("DoughnutChart.xlsx");




2. 使用Worksheetscollection.addcopy()方法将工作表从Excel文件复制到另一个现有的Excel文件:

2. Use the Worksheetscollection.addcopy() method to copy a worksheet from an Excel file to another existing Excel file:

//Load first Excel 
Workbook workbook1 = new Workbook();
workbook1.LoadFromFile("Vendor.xlsx");
//Get sheet1
Worksheet sheet1 = workbook1.Worksheets[0];
//Load second Excel
Workbook workbook2 = new Workbook();
workbook2.LoadFromFile("Report.xlsx");
//Copy
Worksheet sheet2 = workbook2.Worksheets.AddCopy(sheet1);
sheet2.Name = "Copy";
//Save file
workbook2.SaveToFile("Report.xlsx");





这篇关于如何将Excel工作表从一个工作簿复制到另一个工作簿,相关的C#代码保持不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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