In Excel, worksheets are part of a workbook, a workbook can consist of one or more worksheets, and a workbook can be said to be an Excel document, and because of this, the copy of an Excel worksheet is divided into two types: copying within the same document and copying between different documents. This article focuses on how to copy Excel worksheets (including data, pictures, and formatting) in the same document or from one document to another in C #, hoping to help a friend with the same problem (see Tutorial If there is something unclear).
First step: Create a new console project and add references and namespaces.
Using Spire.xls;
Step Two: Create a new Workbook object and load the Excel document.
Workbook Workbook = new Workbook (); Workbook. LoadFromFile ("Commodity statistics. xlsx");
Step three: get the first worksheet and add a new worksheet.
Worksheet Worksheet = workbook. worksheets[0];//Add a new worksheet and name workbook. Worksheets.add ("copied Sheet1");
If you need to copy within the same document see step fourth, if you want to copy to another Excel document, see step fifth.
Fourth Step: Copy the first worksheet data, pictures and formats to the new worksheet.
Workbook. WORKSHEETS[1]. CopyFrom (workbook. Worksheets[0]);
Fifth Step: get the first worksheet by calling worksheet. Clone () method to copy data, pictures, and formatting.
Worksheet newsheet = (Worksheet) Worksheet. Clone (worksheet. Parent); workbook. Worksheets.add (newsheet);
Sixth step: save and reopen the document.
Workbook. SaveToFile ("copy.xlsx"); System.Diagnostics.Process.Start ("copy.xlsx");
Copied to the same Excel document:
Copy to another Excel document:
All code:
Using Spire.xls;namespace copy_worksheet{ class program { static void Main (string[] args) { Workbook Workbook = new Workbook (); Workbook. LoadFromFile ("Commodity statistics. xlsx"); Worksheet Worksheet = workbook. Worksheets[0]; Copy to the same Excel document workbook. Worksheets.add ("copied Sheet1"); Workbook. WORKSHEETS[1]. CopyFrom (workbook. Worksheets[0]); Copy to another Excel document /*worksheet newsheet = (Worksheet) Worksheet. Clone (worksheet. Parent); Workbook. Worksheets.add (newsheet); * * workbook. SaveToFile ("copy.xlsx"); System.Diagnostics.Process.Start ("copy.xlsx"); }
C # Copy an Excel worksheet as is