C# split excel sheet

For the content in the huge data table, if you want to split part of the data in a worksheet and save it as a new worksheet, how to achieve it? The following article will provide the method to achieve. The component Spire.XLS for .NET is used in this method. Before the code operation, you need to install the component and add the dll file that references the component to the project program. For details, please refer to the following. This article is reproduced from http://www.cnblogs.com/Yesi/p/5213624.html

The original Excel file is as follows:



 Below, this table will be split into three different Excel worksheets based on different departments

using Spire.Xls;
 
namespace splitworksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize a Workbook class object and load the worksheet file that needs to be split
            Workbook bookOriginal = new Workbook();
            bookOriginal.LoadFromFile("Information table.xlsx");
            //Get the first worksheet in the workbook
            Worksheet sheet = bookOriginal.Worksheets[0];
           
            //Create a new Workbook class object and add an empty worksheet to it.
            Workbook newBook1 = new Workbook();
            newBook1.CreateEmptySheets(1);
            //Get the first worksheet of newBook1, then get the data from the second row to the eighth row (sales department) in the source excel worksheet, and copy them to the first worksheet of newBook1.
            Worksheet newSheet1 = newBook1.Worksheets[0];
            CellRange range1 = sheet.Range[2, 1, 8, sheet.LastColumn];
            newSheet1.Copy(range1, newSheet1.Range[1, 1]);
 
            //Create a new Workbook object newbook2, get the data from the ninth row to the fifteenth row (human resources department) in the source excel worksheet and copy them to newbook2.
            Workbook newBook2 = new Workbook();
            newBook2.CreateEmptySheets(1);
            Worksheet newSheet2 = newBook2.Worksheets[0];
            CellRange range2 = sheet.Range[9, 1, 15, sheet.LastColumn];
            newSheet2.Copy(range2, newSheet2.Range[1, 1]);

            //Delete the data from the second row to the fifteenth row in the source excel file, and the data in the remaining row (R&D department) will be saved as another new excel file. Note that the 14 here represents not the line number but the line number.
            sheet.DeleteRow(2, 14);

            //Save these three excel files and name them after the department
            newBook1.SaveToFile("Sales Department.xlsx", ExcelVersion.Version2007);
            newBook2.SaveToFile("HR.xlsx", ExcelVersion.Version2007);
            bookOriginal.SaveToFile("R&D Department.xlsx", ExcelVersion.Version2007);
        }
    }
}

 The split document looks like this:



 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326421978&siteId=291194637