C#: Remove Worksheets from a Workbook

2024-07-10 06:09:00 Written by Koohji

Simplifying your Excel workbooks by removing redundant or unused worksheets can be a beneficial organizational practice. This process allows you to eliminate clutter and improve file structure by focusing only on the most relevant data. Removing unneeded worksheets frees up storage space, streamlines navigation, and keeps your workbooks clean and efficient.

In this article, you will learn how to remove worksheets from an Excel workbook in C# by using the Spire.XLS for .NET library.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Remove a Worksheet by Its Index from a Workbook in C#

Spire.XLS for .NET provides the WorksheetsCollection.RemoveAt(int index) method, which allows you to remove a specific worksheet by its index from a workbook. Here are the detailed steps:

  • Create a Workbook object.
  • Load an Excel file from a given path.
  • Get the worksheets collection from the document using Workbook.Worksheets property.
  • Remove a worksheet by its index using WorksheetsCollection.RemoveAt(int index) method.
  • Save the workbook to a different Excel document.
  • C#
using Spire.Xls;
using Spire.Xls.Collections;

namespace RemoveWorksheetByIndex
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook wb = new Workbook();

            // Load an Excel file
            wb.LoadFromFile(@"C:\Users\Administrator\Desktop\Input.xlsx");

            // Get the worksheets collection from the document
            WorksheetsCollection worksheets = wb.Worksheets;

            // Remove a specific worksheet by its index
            worksheets.RemoveAt(0);

            // Save the workbook to a different Excel file
            wb.SaveToFile("RemoveByIndex.xlsx", ExcelVersion.Version2016);

            // Dispose resources
            wb.Dispose();
        }
    }
}

Remove a Worksheet by Its Name from a Workbook in C#

If you already know the name of the worksheet that you want to remove, you can do so by using the WorksheetsCollection.Remove(string sheetName) method. The detailed steps are as follows:

  • Create a Workbook object.
  • Load an Excel file from a given path.
  • Get the worksheets collection from the document using Workbook.Worksheets property.
  • Remove a worksheet by its name using WorksheetsCollection.Remove(string sheetName) method.
  • Save the workbook to a different Excel document.
  • C#
using Spire.Xls;
using Spire.Xls.Collections;

namespace RemoveWorksheetByName
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook wb = new Workbook();

            // Load an Excel file
            wb.LoadFromFile(@"C:\Users\Administrator\Desktop\Input.xlsx");

            // Get the worksheets collection from the document
            WorksheetsCollection worksheets = wb.Worksheets;

            // Remove a specific worksheet by its name
            worksheets.Remove("sheet2")

            // Save the workbook to a different Excel file
            wb.SaveToFile("RemoveByName.xlsx", ExcelVersion.Version2016);

            // Dispose resources
            wb.Dispose();
        }
    }
}

Remove All Worksheets from a Workbook at Once in C#

To remove all worksheets at once, you can use the WorksheetsCollection.Clear() method. Here are the detailed steps:

  • Create a Workbook object.
  • Load an Excel file from a given path.
  • Get the worksheets collection from the document using Workbook.Worksheets property.
  • Remove all worksheet at once using WorksheetsCollection.Clear() method.
  • Save the workbook to a different Excel document.
  • C#
using Spire.Xls;
using Spire.Xls.Collections;

namespace RemoveAllWorksheets
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook wb = new Workbook();

            // Load an Excel file
            wb.LoadFromFile(@"C:\Users\Administrator\Desktop\Input.xlsx");

            // Get the worksheets collection from the document
            WorksheetsCollection worksheets = wb.Worksheets;

            // Remove all worksheets
            worksheets.Clear();

            // Save the workbook to a different Excel file
            wb.SaveToFile("RemoveAllWorksheets.xlsx", ExcelVersion.Version2016);

            // Dispose resources
            wb.Dispose();
        }
    }
}

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

There is no concept of expiration date defined in the PDF specifications format, however, there is a workaround that we can apply expiration using JavaScript. Spire.PDF supports to add java script actions to PDF files as well. This article presents how to add a JavaScript expiration date to a PDF document using Spire.PDF in C# and VB.NET.

Step 1: Create an object of PdfDocument class and add a blank page to it.

PdfDocument doc = new PdfDocument();
doc.Pages.Add();

Step 2: Define the JavaScript code.

string javaScript = "var rightNow = new Date();"
                    + "var endDate = new Date('October 20, 2016 23:59:59');"
                    + "if(rightNow.getTime() > endDate)"
                    + "app.alert('This Document has expired, please contact us for a new one.',1);"
                    + "this.closeDoc();";

Step 3: Create a PdfJavaScriptAction object that performs the java script action in PDF document.

PdfJavaScriptAction js = new PdfJavaScriptAction(javaScript);

Step 4: Set the JavaScript as PDF open action.

doc.AfterOpenAction = js;

Step 5: Save the file.

doc.SaveToFile("ExpiryDate.pdf", FileFormat.PDF);

Output:

How to Add Expiry Date to PDF Files in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Actions;

namespace AddExpiryDate
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.Pages.Add();

            string javaScript = "var rightNow = new Date();"
                     + "var endDate = new Date('October 20, 2016 23:59:59');"
                     + "if(rightNow.getTime() > endDate)"
                     + "app.alert('This Document has expired, please contact us for a new one.',1);"
                     + "this.closeDoc();";
            PdfJavaScriptAction js = new PdfJavaScriptAction(javaScript);
            doc.AfterOpenAction = js;
            doc.SaveToFile("ExpiryDate.pdf", FileFormat.PDF);
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Actions

Namespace AddExpiryDate
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As PdfDocument = New PdfDocument()
doc.Pages.Add()
 
String javaScript = "var rightNow = new Date();"
                    + "var endDate = new Date('October 20, 2016 23:59:59');"
                    + "if(rightNow.getTime() > endDate)"
                    + "app.alert('This Document has expired, please contact us for a new one.',1);"
                    Dim "this.closeDoc();" As +
Dim js As PdfJavaScriptAction = New PdfJavaScriptAction(javaScript)
doc.AfterOpenAction = js
doc.SaveToFile("ExpiryDate.pdf", FileFormat.PDF)
		End Sub
	End Class
End Namespace

Spire.XLS supports to protect the whole excel workbook and specified worksheet with password. When we deal with the protected worksheet, sometimes we need to allow users to edit some specified ranges of the excel worksheet. This article will focus on demonstrating how to use the AddAllowEditRange method offered by Spire.XLS to set the specified range on a protected worksheet to be editable by users.

Step 1: Initialize an instance of Workbook and load the document from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the workbook.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Define the specified ranges of Excel to allow users to edit while sheet is protected.

sheet.AddAllowEditRange("AAA", sheet.Range["C2:D8"], "");

Step 4: Protect the worksheet.

sheet.Protect("AAA", SheetProtectionType.All);

Step 5: Save the document to file.

workbook.SaveToFile("AllowEditRange.xlsx", ExcelVersion.Version2010);

Effective screenshot of Allow users to edit ranges:

Allow users to edit ranges for the protected Excel worksheet in C#

Full codes:

using Spire.Xls;
namespace EditRanges
{
    class Program
    {

        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");

            Worksheet sheet = workbook.Worksheets[0];

            sheet.AddAllowEditRange("AAA", sheet.Range["C2:D8"], "");
            sheet.Protect("AAA", SheetProtectionType.All);

            workbook.SaveToFile("AllowEditRange.xlsx", ExcelVersion.Version2010);

        }
    }
}
page 204