The sample demonstrates how to define named cell references or ranges in excel workbook.

Download MiscDataTable.xls

XLS Report Silverlight

2011-08-30 09:21:38 Written by Administrator

The sample demonstrates how to work with MarkerDesign in Silverlight via Spire.XLS.

Download template xls file.

Download data table file.

Download merged result file.

This section aims at providing a detail solution for developers on how to convert specific worksheet cells to image via this .NET Excel component Spire.XLS for .NET in C#, VB.NET. This Excel library helps us quickly convert certain excel cells to different image formats such as jpeg, png, bmp, tiff, gif, ico, emf, exif etc.

When we convert worksheet to image, Spire.XLS for .NET provides us a method: Spire.Xls.Worksheet.SaveToImage(int firstRow, int firstColumn, int lastRow, int lastColumn); As we see, there are four parameters passed in this method. These four parameters determine the certain range of cells. After deciding the cell range, we can successfully convert cells to image. Now, let us see the whole task step by step.

Step 1: Create a template Excel Workbook in MS Excel

I create a new Excel file in MS Excel and add some data which have different formats in the first sheet, here is a screenshot of created file.

Excel to Image

Step 2: Download and Install Spire.XLS for .NET

Spire.XLS for .NET is an Excel Api which enables users to quickly generate, read, edit and manipulate Excel files on .NET Platform. Here you can download Spire.XLS for .NET and install it on your development computer. After installing it, Spire.XLS for .NET will run in evaluation mode which is the same when you install other Spire components. This evaluation mode has no time limit.

Step 3: Create a project and Add References

We can create a new project of Console Application either in C# or VB.NET. I create in C#, but we can choose VB.NET too.

In this project, we need to add references in our project. Apart from adding System.Drawing, we will use Spire.XLS for .NET, so we also have to add Spire.Xls.dll, Spire.Common.dll and Spire.License.dll in our download Bin folder of Spire.Xls. Here we can see the default path: "..\Spire.XLS\Bin\NET4.0\Spire.XLS.dll"

Step 4: Convert Specific Worksheet Cells to Image

In this step, first we can initialize a new object of the class Spire.Xls.Workbook, then, load the template Excel file. Since I want to convert cells in the first sheet to image, I need get the first worksheet data in Excel file. You also can get other worksheet data. Finally specify cell range and save the cells in the range as image file. Spire.XLS for .NET supports 12 image formats: Bmp, Emf, Equals, Exif, Gif, Icon, Jpeg, MemoryBmp, Png, ReferenceEquals, Tiff and Wmf.

[C#]
using System.Drawing;
using System.Drawing.Imaging;
using Spire.Xls;
using Spire.Xls.Converter;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize a new Workbook object
            Workbook workbook = new Workbook();
            //Open Template Excel file
            workbook.LoadFromFile(@"..\excel to image.xlsx");
            //Get the first wirksheet in Excel file
            Worksheet sheet = workbook.Worksheets[0];
            //Specify Cell Ranges and Save to certain Image formats
            sheet.SaveToImage(1, 1, 6, 3).Save("image1.png",ImageFormat.Png);
            sheet.SaveToImage(7, 1, 12, 3).Save("image2.jpeg", ImageFormat.Jpeg);
            sheet.SaveToImage(13, 1, 18, 3).Save("image3.bmp", ImageFormat.Bmp);
        }
    }
}
          
[VB.NET]
Imports System.Drawing
Imports System.Drawing.Imaging
Imports Spire.Xls
Imports Spire.Xls.Converter

Namespace ConsoleApplication1
	Class Program
		Private Shared Sub Main(args As String())
			'Initialize a new Workbook object
			Dim workbook As New Workbook()
			'Open Template Excel file
			workbook.LoadFromFile("..\excel to image.xlsx")
			'Get the first wirksheet in Excel file
			Dim sheet As Worksheet = workbook.Worksheets(0)
			'Specify Cell Ranges and Save to certain Image formats
			sheet.SaveToImage(1, 1, 6, 3).Save("image1.png", ImageFormat.Png)
			sheet.SaveToImage(7, 1, 12, 3).Save("image2.jpeg", ImageFormat.Jpeg)
			sheet.SaveToImage(13, 1, 18, 3).Save("image3.bmp", ImageFormat.Bmp)
		End Sub
	End Class
End Namespace

Result Task

After executing above code, cells in the first worksheet named "Sheet1" has been converted to three images. They are named "image1.png", "image2.jpeg" and "image3.bmp". You can see them as below:

Excel to Image

In this section, I have introduced how we can convert specific cells to image by using Spire.XLS for .NET. I sincerely hope it can help you and give you some insight.

Spire.XLS for .NET offers fast speed, high efficiency and reliability to satisfy development application requirements. As you see above, the results do show that Spire.XLS for .NET benefit customers from years of research.

We appreciate any kind of queries, comments and suggestions at E-iceblue Forum. We promise a quick reply within minutes or hours as we can.

Question:

I want to replace text in a word template with HTML. I know how to append HTML to last paragraph but this paragraph is in the middle of word document.

Answer:

Below is a VB project demo about text replacing with multiple paragraphs and html, hope it will help you.

TextReplaceWithMultipleParagraph2.zip

If this doesn't answer your question, please do not hesitate to add your question in our forum. Our technical support will answer soon (we promise response within 1 business day)!

Question:

I'm trying to set an array of values into a range in Excel Worksheet. This is possible via Microsoft Excel object and allows setting values very quickly. How to use Spire.XLS to manage it?

Answer:

It is possible to output an array of data to a range of worksheet via Spire.XLS. Using arrays sheet.InsertArray() method and the following sample source codes for your reference would be helpful.

using Spire.Xls;
namespace SetArrayofValues
{
    class Program
    {
            private void SetArrayValueExample()
        {
            Workbook workbook = new Workbook();
            workbook.CreateEmptySheets(1);

            Worksheet sheet = workbook.Worksheets[0];

            int maxRow = 10000;
            //int maxRow = 5;
            int maxCol = 200;

            //int maxCol = 5;
            object[,] myarray = new object[maxRow + 1, maxCol + 1];
            bool[,] isred = new bool[maxRow + 1, maxCol + 1];
            for (int i = 0; i <= maxRow; i++)
                for (int j = 0; j <= maxCol; j++)
                {
                    myarray[i, j] = i + j;
                    if ((int)myarray[i, j] > 8)
                        isred[i, j] = true;
                }

            sheet.InsertArray(myarray, 1, 1);

            workbook.SaveToFile("test.xls",ExcelVersion.Version97to2003);
        }


        }
    }

If this doesn't answer your question, please do not hesitate to add your question in our forum. Our technical support will answer soon (we promise response within 1 business day)!

How to Merge Cells in Excel Using C# and VB.NET

Working with large Excel files often means merging rows, columns, or specific cell ranges to keep the data clean and easy to read. You can merge cells in Excel using C# or VB.NET with just a few lines of code and even center the content both horizontally and vertically for a professional look. Whether it’s combining entire rows, joining columns, or formatting a selected range, these examples show how to automate the process and improve your workflow.

If you often work with Excel files in .NET projects, handling tasks like merging cells, formatting data, or generating reports, you’ll want a tool that makes the process fast and reliable. Spire.XLS is a lightweight library that lets you create, read, and modify Excel files directly in C# or VB.NET—without relying on Microsoft Office. You can add it to your project in seconds via NuGet:

PM> Install-Package Spire.XLS

From there, you’re ready to start automating your Excel workflow.

Merge Rows or Columns in Excel using C#

Merging rows or columns in Excel is a common way to organize data and create professional-looking spreadsheets. For example, you can merge the first row across multiple columns to form a clear, centered table header. Using C# code, this process can be automated easily, saving time and ensuring consistency across large Excel files.

Here's the code example of merging the first row and centering it in Excel using C#:

using Spire.Xls;
namespace MergeCells
{

    class Program
    {

        static void Main(string[] args)
        {
            // Create a Workbook instance and load an Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("\\Population.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Merge the first row
            sheet.Rows[0].Merge();
            // Merge the first column
            //sheet.Columns[0].Merge();

            // Set the alignment to center horizontally and vertically
            sheet.Rows[0].Style.HorizontalAlignment = HorizontalAlignType.Center;
            sheet.Rows[0].Style.VerticalAlignment = VerticalAlignType.Center;

            // Save the Excel file
            workbook.SaveToFile("\\Mergerowsandcenter.xls");

        }
    }
}

Here's the preview of merging the first row in Excel:

Merge the First Row in an Excel file using C#

Code steps explained:

  • Create a Workbook object and read an Excel file.
  • Get a worksheet.
  • Merge a certain row using Worksheet.Rows[].Merge() method.
  • Set the alignment to center horizontally and vertically by adjusting the Style.HorizontalAlignment and Style.VerticalAlignment properties.
  • Save the modified Excel file.

The C# code above for merging rows in an Excel file can also be used to merge columns, which is indicated with comments in the code.

After merging cells to create a clean table header, you might sometimes need to undo the operation. You can easily unmerge cells in Excel in C# or VB.NET, restoring the original cell layout without affecting your data.

Merge a Specific Cell Range in Excel

Merging a specific cell range in Excel using C# is useful when you want to highlight a section of data, such as a summary row or a group of related columns. The process is very similar to merging entire rows or columns, and you can use the same Merge() method—applied to a CellRange object via Worksheet.Range[].Merge() method. By specifying the exact range to merge, you can create a clear, organized layout that improves readability and automates the operation across multiple sheets or files without manually adjusting each cell.

The code example below demonstrates how to merge the cell range "B6:E6" in an Excel worksheet using C#:

using Spire.Xls;
namespace MergeCells
{

    class Program
    {

        static void Main(string[] args)
        {
            // Create a Workbook instance and load an Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("\\Population.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Merge the particular cell range in Excel 
            sheet.Range["B6:E6"].Merge();

            // Save the Excel file
            workbook.SaveToFile("\\Mergecellrange.xls");

        }
    }
}

Here's the preview of merging a cell range in an Excel file using C#:

Merge a Specified Cell Range in Excel with C#

Merge and Center Cells in Excel using VB.NET

Just like in C#, you can merge and center cells in Excel using VB.NET to create clean table headers or highlight key data sections. The steps are very similar, and the same Merge() method applies to rows, columns, or specific cell ranges. If you want, you can even convert C# examples to VB.NET using our handy C# ↔ VB.NET code converter, making it easy to adapt existing code for your project.

Here's a code example of merging the first row and centering it in Excel using VB.NET:

Imports Spire.Xls

Namespace MergeCells

    Friend Class Program

        Private Shared Sub Main(args As String())
            ' Create a Workbook instance and load an Excel file
            Dim workbook As Workbook = New Workbook()
            workbook.LoadFromFile("E:\Administrator\Python1\input\Population.xlsx")

            ' Get the first worksheet
            Dim sheet As Worksheet = workbook.Worksheets(0)

            ' Merge the first row
            sheet.Rows(0).Merge()
            ' Merge the first column
            'sheet.Columns[0].Merge();

            ' Set the alignment to center horizontally and vertically
            sheet.Rows(0).Style.HorizontalAlignment = HorizontalAlignType.Center
            sheet.Rows(0).Style.VerticalAlignment = VerticalAlignType.Center

            ' Save the Excel file
            workbook.SaveToFile("\Mergerowsandcenter.xls")

        End Sub
    End Class
End Namespace

The Conclusion

By following these examples, you can merge cells in Excel using C#, whether it’s entire rows, columns, or specific ranges. With the help of Spire.XLS, you can merge cells in Excel files automatically without hassle and create clear, professional-looking spreadsheets. Start streamlining your workflow today and get a 30-day free license to try all features without restrictions.

C#/VB.NET: Copy Worksheets in Excel

2011-08-15 07:57:16 Written by Koohji

Excel copy function enables you to not only copy worksheets within Excel workbook but also copy worksheets between different Excel workbooks. This article will introduce solutions to copy worksheets within one Excel workbook and among different workbooks via Spire.XLS for .NET in C#, VB.NET. Besides, all the cell formats in the original Excel worksheets will be completely remained.

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 DLLs files can be either downloaded from this link or installed via NuGet.

  • Package Manager
PM> Install-Package Spire.XLS

Copy Excel Worksheets within Excel Workbook

The following are the steps to duplicate worksheets within an Excel workbook.

  • Initialize an instance of Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Add a new blank sheet to the workbook using WorksheetCollection.Add() method.
  • Copy the original worksheet to the new sheet using Worksheet.CopyFrom() method.
  • Use Workbook.SaveToFile() method to save the changes to another file.
  • C#
  • VB.NET
using Spire.Xls;

namespace CopyExcelworksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the sample Excel
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");

            //Add worksheet and set its name
            workbook.Worksheets.Add("Sheet1_Copy");
         
           //copy worksheet to the new added worksheets
           workbook.Worksheets[1].CopyFrom(workbook.Worksheets[0]);
          
            //Save the Excel workbook.
            workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013);
            System.Diagnostics.Process.Start("Duplicatesheet.xlsx");

        }
    }
}
Imports Spire.Xls

Namespace CopyExcelworksheet
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            'Load the sample Excel
            Dim workbook As Workbook = New Workbook
            workbook.LoadFromFile("Sample.xlsx")
            'Add worksheet and set its name
            workbook.Worksheets.Add("Sheet1_Copy")
            'copy worksheet to the new added worksheets
            workbook.Worksheets(1).CopyFrom(workbook.Worksheets(0))
            'Save the Excel workbook.
            workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013)
            System.Diagnostics.Process.Start("Duplicatesheet.xlsx")
        End Sub
    End Class
End Namespace

C#/VB.NET: Copy Worksheets in Excel

Copy Excel Worksheets between Excel Workbooks

The following are the steps to duplicate worksheets within an Excel workbook.

  • Initialize an instance of Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the first worksheet.
  • Load another Excel sample document
  • Add a new blank sheet to the second workbook using WorksheetCollection.Add() method.
  • Copy the original worksheet to the new sheet using Worksheet.CopyFrom() method.
  • Use Workbook.SaveToFile() method to save the changes to another file.
  • C#
  • VB.NET
using Spire.Xls;

namespace CopyExcelworksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the sample Excel and get the first worksheet
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            //Load the second Excel workbook
            Workbook workbook2 = new Workbook();
            workbook2.LoadFromFile("New.xlsx");
            //Add a new worksheet and set its name
            Worksheet targetWorksheet = workbook2.Worksheets.Add("added");
            //Copy the original worksheet to the new added worksheets
            targetWorksheet.CopyFrom(sheet);
            //Save the Excel workbook.
            workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013);
            System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx");

        }
    }
}
Imports Spire.Xls

Namespace CopyExcelworksheet
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            'Load the sample Excel and get the first worksheet
            Dim workbook As Workbook = New Workbook
            workbook.LoadFromFile("Sample.xlsx")
            Dim sheet As Worksheet = workbook.Worksheets(0)
            'Load the second Excel workbook
            Dim workbook2 As Workbook = New Workbook
            workbook2.LoadFromFile("New.xlsx")
            'Add a new worksheet and set its name
            Dim targetWorksheet As Worksheet = workbook2.Worksheets.Add("added")
            'Copy the original worksheet to the new added worksheets
            targetWorksheet.CopyFrom(sheet)
            'Save the Excel workbook.
            workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013)
            System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx")
        End Sub
    End Class
End Namespace

C#/VB.NET: Copy Worksheets in Excel

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.

Decrypt Excel Worksheet in C#, VB.NET

2011-08-11 03:06:10 Written by Koohji

Why Decrypt Excel Worksheet?

To protect our Excel file data information, we can encrypt Excel worksheet by setting password. But we may sometimes forget the password and we can't read the excel data information neither. So, if this happens we need decrypt Excel worksheet. It’s not easy to decrypt Excel Worksheet which has been encrypted because the reason why we encrypt it is to prevent it from reading by people without password. And now, we do not have password.

How to Use C#/VB.NET to Decrypt Excel Worksheet?

Spire.XLS for .NET, a .NET Excel component which enables .NET applications to fast generate, read, write and modify Excel document without Microsoft Office Excel Automation can help us decrypt Excel worksheet by using C#/VB.NET.

Spire.XLS for .NET presents a very easy solution for developers/programmers decrypting Excel worksheet. We just need sheet.Unprotect( "password" ) method and normal encrypted excel worksheet can be decrypted.

Download Spire.XLS for .NET (or Spire.Office) with .NET framework 2.0 (or above) together. The sample code below will show you how to use C#/VB.NET decrypt Excel worksheet through Spire.XLS for .NET.

[C#]
using Spire.Xls;
namespace DescryptWorksheet
{
    class Program
    {

        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("test.xls");
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Unprotect("password");
            workbook.SaveToFile("result.xls", ExcelVersion.Version97to2003);

        }
    }
}
[VB.NET]

Spire.XLS allows users to operate Excel document directly such as save to stream, save as web response, copy, lock/unlock worksheet, set up workbook properties, etc. As a professional .NET Excel component, it owns the ability of inserting content into Excel document, formatting cells and converting Excel documents to popular office file formats. Spire.XLS for .NET supports Excel 97-2003, Excel 2007 and Excel 2010.

When sharing Excel files with other people or sending files out of your organization, you may want to protect sensitive data from being changed, moved, or deleted. The easiest way to prevent accidental or deliberate changes in the contents is to restrict editing on a worksheet or password protect an entire workbook. In this article, you will learn how to protect and unprotect a workbook or a worksheet in C# and VB.NET using Spire.XLS for .NET.

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

Password Protect an Entire Workbook in C# and VB.NET

By encrypting an Excel document with a password, you ensure that only you and authorized individuals can read or edit it. The following are the steps to password protect a workbook using Spire.XLS for .NET.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Protect the workbook using a password using Workbook.Protect() method.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

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

            //Protect workbook with a password
            workbook.Protect("psd-123");

            //Save the workbook to another Excel file
            workbook.SaveToFile("Encrypted.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Protect or Unprotect Excel Documents

Protect a Worksheet with a Specific Protection Type in C# and VB.NET

If you wish to grant people permission to read your Excel document but restrict the types of modifications they are allowed to make on a worksheet, you can protect the worksheet with a specific protection type. The table below lists a variety of pre-defined protection types under the SheetProtectionType enumeration.

Protection Type Allow users to
Content Modify or insert content.
DeletingColumns Delete columns.
DeletingRows Delete rows.
Filtering Set filters.
FormattingCells Format cells.
FormattingColumns Format columns.
FormattingRows Format rows.
InsertingColumns Insert columns.
InsertingRows Insert rows.
InsertingHyperlinks Insert hyperlinks .
LockedCells Select locked cells.
UnlockedCells Select unlocked cells.
Objects Modify drawing objects.
Scenarios Modify saved scenarios.
Sorting Sort data.
UsingPivotTables Use pivot table and pivot chart.
All Do any operations listed above on the protected worksheet.
None Do nothing on the protected worksheet.

The following are the steps to protect a worksheet with a specific protection type using Spire.XLS for .NET.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Protect the worksheet with a protection type using Worksheet.Protect(string password, SheetProtectionType options) method.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

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

            //Get a specific worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //Protect the worksheet with the permission password and the specific protect type
            worksheet.Protect("psd-permission", SheetProtectionType.None);

            //Save the workbook to another Excel file
            workbook.SaveToFile("ProtectWorksheet.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Protect or Unprotect Excel Documents

Allow Users to Edit Ranges in a Protected Worksheet in C# and VB.NET

In certain cases, you may need to allow users to be able to edit selected ranges in a protected worksheet. The following steps demonstrate how to.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Specify editable cell ranges using Worksheet.AddAllowEditRange() method.
  • Protect the worksheet with a protection type using Worksheet.Protect(string password, SheetProtectionType options) method.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

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

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Add ranges that allow editing
            sheet.AddAllowEditRange("Range One", sheet.Range["A5:A6"]);
            sheet.AddAllowEditRange("Range Two", sheet.Range["A8:B11"]);

            //Protect the worksheet with a password and a protection type
            sheet.Protect("psd-permission", SheetProtectionType.All);

            //Save the workbook to another Excel file
            workbook.SaveToFile("AllowEditRange.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Protect or Unprotect Excel Documents

Unprotect a Password Protected Worksheet in C# and VB.NET

To remove the protection of a password-protected worksheet, invoke the Worksheet.Unprotect() method and pass in the original password as a parameter. The detailed steps are as follows.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Remove the protection using Worksheet.Unprotect(string password) method.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

            //Load an Excel file containing protected worksheet
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\ProtectedWorksheet.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Unprotect the worksheet using the specified password
            sheet.Unprotect("psd-permission");

            //Save the workbook to anther Excel file
            workbook.SaveToFile("UnprotectWorksheet.xlsx", ExcelVersion.Version2016);
        }
    }
}

Remove or Reset Password of an Encrypted Workbook in C# and VB.NET

To remove or reset password of an encrypted workbook, you can use the Workbook.Unprotect() method and the Workbook.Protect() method, respectively. The following steps show you how to load an encrypted Excel document and delete or change the password of it.

  • Create a Workbook object.
  • Specify the open password through Workbook.OpenPassword property.
  • Load the encrypted Excel file using Workbook.LoadFromFile() method.
  • Remove the encryption using Workbook.Unprotect() method. Or change the password using Workbook.Protect() method.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

            //Specify the open password
            workbook.OpenPassword = "psd-123";

            //Load an encrypted Excel file
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.xlsx");

            //Unprotect workbook
            workbook.UnProtect();

            //Reset password
            //workbook.Protect("newpassword");

            //Save the workbook to another Excel file
            workbook.SaveToFile("Unprotect.xlsx", ExcelVersion.Version2016);
        }
    }
}

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.

The most important reason that people lock worksheet when perform tasks in Excel is to protect the original Excel file from editing or modifying by other people. Through Microsoft Excel, you can set the entire Excel worksheet by setting its property as Read Only or just set partial region area cells as Read Only via protecting worksheet. While how to lock worksheet with C#, VB.NET will be the core topic in this section.

Spire.XLS for .NET, as a fast and reliable excel component, enables you to lock your worksheet by setting Worksheet class property: Worksheet.Range.Style.Locked = true. By this component, you can lock any worksheet that you need. In this solution, worksheet one and worksheet two are locked as you view in below picture:

Lock Excel Worksheet

Now, before the detail code, you have to add Spire.Xls dll by download Spire.XLS for .NET.

[C#]
using Spire.Xls;

namespace lock_excel_worksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"..\lock worksheet.xls");
            workbook.Worksheets[0].Range.Style.Locked = true;
            workbook.Worksheets[1].Range.Style.Locked = true;
            workbook.Worksheets[0].Protect("", SheetProtectionType.All);
            workbook.Worksheets[1].Protect("", SheetProtectionType.All);
            workbook.SaveToFile("result.xls",ExcelVersion.Version97to2003);
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace lock_excel_worksheet
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            Dim workbook As Workbook = New Workbook
            workbook.LoadFromFile("..\lock worksheet.xls")
            workbook.Worksheets(0).Range.Style.Locked = true
            workbook.Worksheets(1).Range.Style.Locked = true
            workbook.Worksheets(0).Protect("", SheetProtectionType.All)
            workbook.Worksheets(1).Protect("", SheetProtectionType.All)
            workbook.SaveToFile("result.xls",ExcelVersion.Version97to2003)
        End Sub
    End Class
End Namespace

Spire.XLS allows user to operate Excel document directly such as save to stream, save as web response, copy, lock/unlock worksheet, set up workbook properties, etc. As a professional .NET/Silverlight Excel component, it owns the ability of inserting content into Excel document, formatting cells and converting Excel documents to popular office file formats. Spire.XLS for .NET supports Excel 97-2003, Excel 2007 and Excel 2010.

page 80