C#/VB.NET: Convert Office (Word, Excel, PowerPoint) Files to OpenDocument Format (ODT, ODS, ODP)

What is OpenDocument Format

OpenDocument Format (ODF) is an open and ISO-standard file format for office application files such as word processing documents, spreadsheets and presentations. OpenDocument format has several advantages, for example, it is compatible with MS Office and open-source applications like OpenOffice and LibreOffice, it is platform-independent and does not rely on any office application suite, and it is an open standard that can be implemented by any company in its software.

OpenDocument files can have the following extensions:

  • .odt (word processing documents)
  • .ods (spreadsheets)
  • .odp (presentations)

This article will introduce how to convert Office (Word, Excel, PowerPoint) files to OpenDocument Format (.odt, .ods, .odp) using C# and VB.NET. It includes the following topics:

  • Convert Word Files to OpenDocument Text (.odt)
  • Convert Excel Files to OpenDocument Spreadsheet (.ods)
  • Convert PowerPoint Files to OpenDocument Presentation (.odp)

.NET Library to Convert Office Files to OpenDocument Format

In order to convert Office files to ODF, this article uses Spire.Office for .NET library. You can install Spire.Office for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Office

Alternatively, you can also download the DLL files of Spire.Office for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Convert Word Files to OpenDocument Text (.odt) in C# and VB.NET

The following steps demonstrate how to convert a Word file to OpenDocument Text (.odt) format:

  • Initialize an instance of the Document class.
  • Load a Word file using Document.LoadFromFile(string) method.
  • Save the file to OpenDocument Text (.odt) format using Document.SaveToFile(string, FileFormat) method.

C#

using Spire.Doc;

namespace ConvertWordFilesToODT
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word file
            document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");

            //Save the Word file to OpenDocument Text (.odt) format
            document.SaveToFile("WordToOdt.odt", Spire.Doc.FileFormat.Odt);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace ConvertWordFilesToODT
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word file
            document.LoadFromFile("C:\Users\Administrator\Desktop\Test.docx")

            'Save the Word file to OpenDocument Text (.odt) format
            document.SaveToFile("WordToOdt.odt", Spire.Doc.FileFormat.Odt)
        End Sub
    End Class
End Namespace

Convert Excel Files to OpenDocument Spreadsheet (.ods) in C# and VB.NET

The following steps demonstrate how to convert an Excel file to OpenDocument Spreadsheet (.ods) format:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile(string) method.
  • Save the file to OpenDocument Spreadsheet (.ods) format using Workbook.SaveToFile(string, FileFormat) method.

C#

using Spire.Xls;

namespace ConvertExcelFilesToODS
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.xlsx");

            //Save the Excel file to OpenDocument Spreadsheet (.ods) format
            workbook.SaveToFile("ExcelToOds.ods", Spire.Xls.FileFormat.ODS);
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace ConvertExcelFilesToODS
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Workbook class
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("C:\Users\Administrator\Desktop\Test.xlsx")

            'Save the Excel file to OpenDocument Spreadsheet (.ods) format
            workbook.SaveToFile("ExcelToOds.ods", Spire.Xls.FileFormat.ODS)
        End Sub
    End Class
End Namespace

Convert PowerPoint Files to OpenDocument Presentation (.odp) in C# and VB.NET

The following steps demonstrate how to convert a PowerPoint file to OpenDocument Presentation (.odp) format:

  • Initialize an instance of the Presentation class.
  • Load a PowerPoint file using Presentation.LoadFromFile(string) method.
  • Save the file to OpenDocument Presentation (.odp) format using Presentation.SaveToFile(string, FileFormat) method.

C#

using Spire.Presentation;

namespace ConvertPowerPointFilesToODP
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Presentation class
            Presentation presentation = new Presentation();
            //Load a PowerPoint file
            presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.pptx");

            //Save the PowerPoint file to OpenDocument Presentation (.odp) format
            presentation.SaveToFile("PowerPointToOdp.odp", Spire.Presentation.FileFormat.ODP);
        }
    }
}

VB.NET

Imports Spire.Presentation

Namespace ConvertPowerPointFilesToODP
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Presentation class
            Dim presentation As Presentation = New Presentation()
            'Load a PowerPoint file
            presentation.LoadFromFile("C:\Users\Administrator\Desktop\Test.pptx")

            'Save the PowerPoint file to OpenDocument Presentation (.odp) format
            presentation.SaveToFile("PowerPointToOdp.odp", Spire.Presentation.FileFormat.ODP)
        End Sub
    End Class
End Namespace

Conclusion

This article demonstrated how to convert Office files to OpenDocument Format (ODF) using Spire.Office for .NET library. Besides the conversion from Office to ODF, you can also use the library to convert Office files to lots of other file formats, such as PDF, HTML, images and many more.

C#/VB.NET: Convert Word Doc or Docx to PDF

Word and PDF are two of the most commonly used file formats today. In some cases, you may need to convert Word documents to PDF in order to preserve the document layout while opening them on different systems or devices. In this article, I will demonstrate how to convert Word documents to PDF, PDF/A and password protected PDF using C# and VB.NET.

Installation

To convert Word documents to PDF, this article uses Spire.Doc for .NET. You can install Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Doc

Alternatively, you can also download the DLL files of Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Convert Word to PDF in C# and VB.NET

Spire.Doc offers a Document.SaveToFile(string, FileFormat) method which allows you to convert a Word document to PDF along with lots of other popular file formats.  

The following steps demonstrate how to convert a Word document to PDF:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile(string) method.
  • Save the Word document to PDF using Document.SaveToFile(string, FileFormat) method.

C#

using Spire.Doc;

namespace ConvertWordToPDF
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            //Save the document to PDF
            document.SaveToFile("WordToPdf.pdf", FileFormat.PDF);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace ConvertWordToPDF
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("C:\Users\Administrator\Desktop\Sample.docx")

            'Save the document to PDF
            document.SaveToFile("WordToPdf.pdf", FileFormat.PDF)
        End Sub
    End Class
End Namespace

Convert Word to PDF/A in C# and VB.NET

Sometimes, you may need to convert Word to PDF/A for long document archiving purposes. Spire.Doc allows you to covert a Word document to the following list of PDF/A documents:

  • PDF/A-1a
  • PDF/A-1b
  • PDF/A-2a
  • PDF/A-2b
  • PDF/A-3a
  • PDF/A-3b
  • PDF/X-1a:2001

The following steps demonstrate how to convert a Word document to PDF/A:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile(string) method.
  • Initialize an instance of the ToPdfParameterList class.
  • Specify the conformance level of the converted PDF through ToPdfParameterList.PdfConformanceLevel property.
  • Save the Word document to PDF/A using Document.SaveToFile(string, ToPdfParameterList) method.

C#

using Spire.Doc;

namespace ConvertWordToPDFA
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document(false);
            //Load a Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            //Initialize an instance of the ToPdfParameterList class
            ToPdfParameterList parameterList = new ToPdfParameterList();
            //Specify the conformance level of the converted pdf
            parameterList.PdfConformanceLevel = Spire.Pdf.PdfConformanceLevel.Pdf_A1A;

            //Save the Word document to PDF/A
            document.SaveToFile("WordToPdfA.pdf", parameterList);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace ConvertWordToPDFA
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document(False)
            'Load a Word document
            document.LoadFromFile("C:\Users\Administrator\Desktop\Sample.docx")

            'Initialize an instance of the ToPdfParameterList class
            Dim parameterList As ToPdfParameterList = New ToPdfParameterList()
            'Specify the conformance level of the converted pdf
            parameterList.PdfConformanceLevel = Spire.Pdf.PdfConformanceLevel.Pdf_A1A

            'Save the Word document to PDF/A
            document.SaveToFile("WordToPdfA.pdf", parameterList)
        End Sub
    End Class
End Namespace

Convert Word to Password Protected PDF in C# and VB.NET

If you want to prevent the converted PDF document from unauthorized viewing, you can encrypt it with a password during the conversion. The following are the detailed steps:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile(string) method.
  • Initialize an instance of the ToPdfParameterList class.
  • Set open password for the converted PDF using ToPdfParameterList.PdfSecurity.Encrypt(string) method.
  • Save the Word document to password protected PDF using Document.SaveToFile(string, ToPdfParameterList) method.

C#

using Spire.Doc;

namespace ConvertWordToEncryptedPDF
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document(false);
            //Load a Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            //Initialize an instance of the ToPdfParameterList class
            ToPdfParameterList parameterList = new ToPdfParameterList();
            //Set the open password of the converted pdf
            parameterList.PdfSecurity.Encrypt("password");

            //Save the Word document to password protected PDF
            document.SaveToFile("WordToPassWordProtectedPdf.pdf", parameterList);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace ConvertWordToEncryptedPDF
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document(False)
            'Load a Word document
            document.LoadFromFile("C:\Users\Administrator\Desktop\Sample.docx")

            'Initialize an instance of the ToPdfParameterList class
            Dim parameterList As ToPdfParameterList = New ToPdfParameterList()
            'Set the open password of the converted pdf
            parameterList.PdfSecurity.Encrypt("password")

            'Save the Word document to password protected PDF
            document.SaveToFile("WordToPassWordProtectedPdf.pdf", parameterList)
        End Sub
    End Class
End Namespace

C#/VB.NET: Create Tagged PDF

A tagged PDF is a PDF document containing tags. These tags can help screen readers or other assistive technologies identify the structure of the document and read its content. Creating PDFs with tags is a great way to make your documents accessible to more people, especially those with vision impairments. In this article, I will demonstrate how to create tagged PDF documents using C# and VB.NET.

Installation

In order to create tagged PDFs, this article uses a third-party library called Spire.PDF for .NET.

You can install Spire.PDF for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.PDF

Alternatively, you can also download the API from the official website and extract the package, then add the DLL files under the BIN folder to your project as references.

Create a Tagged PDF in C# and VB.NET

Spire.PDF provides the PdfTaggedContent class to generate tagged PDF documents. You can include various structural elements in a tagged PDF document, including heading, paragraph, figure, table, link, list, and many more. The full list of the supported structural elements can be found under the PdfStandardStructTypes enumeration.

The following are the main steps to create a tagged PDF with various structural elements using C# and VB.NET:

  • Initialize an instance of the PdfDocument class and add a page to it using PdfDocument.Pages.Add() method.
  • Set the tab order of the page using PdfPageBase.SetTabOrder(TabOrder) method.
  • Initialize an instance of the PdfTaggedContent class and pass the PdfDocument instance to the class constructor as a parameter.
  • Set the language and title of the document.
  • Add a document element which is the root element of a structure tree to the document using PdfTaggedContent.StructureTreeRoot.AppendChildElement(PdfStandardStructTypes) method.
  • Add a heading/paragraph/list/figure/table/ link element under the document element using PdfStructureElement.AppendChildElement(PdfStandardStructTypes) method.
  • Add a start tag to indicate the beginning of the element using PdfStructureElement.BeginMarkedContent() method.
  • Specify the element content and draw it onto the page.
  • Add an end tag to indicate the ending of the element using PdfStructureElement.EndMarkedContent() method.
  • Save the result document to a PDF file using PdfDocument.SaveToFile() method.

C#

using Spire.Pdf;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using Spire.Pdf.Interchange.TaggedPdf;
using Spire.Pdf.Lists;
using Spire.Pdf.Tables;
using System.Data;
using System.Drawing;

namespace CreateTaggedPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the PdfDocument class
            PdfDocument doc = new PdfDocument();

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(20));

            //Set tab order
            page.SetTabOrder(TabOrder.Structure);

            //Initialize an instance of the PdfTaggedContent class
            PdfTaggedContent taggedContent = new PdfTaggedContent(doc);

            //Set language and title
            taggedContent.SetLanguage("en-US");
            taggedContent.SetTitle("Tagged PDF");

            //Set PDF/UA-1 compliance
            taggedContent.SetPdfUA1Identification();

            //Create font and brush
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 14), true);
            PdfSolidBrush brush = new PdfSolidBrush(Color.Black);

            //Add a document element which is the root element of any structure tree
            PdfStructureElement document = taggedContent.StructureTreeRoot.AppendChildElement(PdfStandardStructTypes.Document);

            //Add a heading element
            PdfStructureElement heading1 = document.AppendChildElement(PdfStandardStructTypes.HeadingLevel1);
            heading1.BeginMarkedContent(page);
            string headingText = "What Is C#?";
            page.Canvas.DrawString(headingText, font, brush, new PointF(0, 0));
            heading1.EndMarkedContent(page);

            //Add a paragraph element 
            PdfStructureElement paragraph = document.AppendChildElement(PdfStandardStructTypes.Paragraph);
            paragraph.BeginMarkedContent(page);
            string paragraphText = "C# is pronounced C-Sharp. It is an object-oriented programming language created by Microsoft that runs on the.NET Framework." + "C# has roots from the C family, and the language is close to other popular languages like C++ and Java. The first version was released in year 2002."+
              "The latest version, C# 11, was released in November 2022. C# can be used for:";
            RectangleF rect = new RectangleF(0, 30, page.Canvas.ClientSize.Width, page.Canvas.ClientSize.Height);
            page.Canvas.DrawString(paragraphText, font, brush, rect);
            paragraph.EndMarkedContent(page);

            //Add an unordered list element
            PdfStructureElement listElement = document.AppendChildElement(PdfStandardStructTypes.List);
            listElement.BeginMarkedContent(page);
            string listContent = "Mobile applications\n"
                    + "Desktop applications\n"
                    + "Web applications\n"
                    + "Web services\n"
                    + "Web sites\n"
                    + "Games\n"
                    + "And many more!";
            PdfMarker marker = new PdfMarker(PdfUnorderedMarkerStyle.Asterisk);
            marker.Font = font;
            PdfList list = new PdfList(listContent);
            list.Font = font;
            list.Indent = 2;
            list.TextIndent = 4;
            list.Brush = brush;
            list.Marker = marker;
            list.Draw(page, 0, 100);
            listElement.EndMarkedContent(page);

            //Add a figure element
            PdfStructureElement figure = document.AppendChildElement(PdfStandardStructTypes.Figure);
            figure.BeginMarkedContent(page);
            PdfImage image = PdfImage.FromFile(@"Csharp.png");
            page.Canvas.DrawImage(image, new PointF(0, 230));
            figure.EndMarkedContent(page);

            //Add a table element
            PdfStructureElement table = document.AppendChildElement(PdfStandardStructTypes.Table);
            table.BeginMarkedContent(page);
            PdfTable pdfTable = new PdfTable();
            pdfTable.Style.DefaultStyle.Font = font;
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Year");
            dataTable.Columns.Add("Product");
            dataTable.Columns.Add("Sales");
            dataTable.Rows.Add(new string[] { "2020", "Components", "$20,000" });
            dataTable.Rows.Add(new string[] { "2021", "Bikes", "$6,300" });
            pdfTable.DataSource = dataTable;
            pdfTable.Style.ShowHeader = true;
            pdfTable.Draw(page.Canvas, new PointF(0, 320), 300f);
            table.EndMarkedContent(page);

            //Add a link element
            PdfStructureElement link = document.AppendChildElement(PdfStandardStructTypes.Link);
            link.BeginMarkedContent(page);
            PdfTextWebLink link2 = new PdfTextWebLink();
            link2.Text = "www.google.com";
            link2.Url = "https://www.google.com";
            link2.Font = font;
            link2.Brush = brush;
            link2.DrawTextWebLink(page.Canvas, new PointF(0, 390));
            link.EndMarkedContent(page);            

            //Save the result document
            doc.SaveToFile("CreateTaggedPdf.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Annotations
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Interchange.TaggedPdf
Imports Spire.Pdf.Lists
Imports Spire.Pdf.Tables
Imports System.Data
Imports System.Drawing

Namespace CreateTaggedPDF
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the PdfDocument class
            Dim doc As PdfDocument = New PdfDocument()

            'Add a page
            Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, New PdfMargins(20))

            'Set tab order
            page.SetTabOrder(TabOrder.[Structure])

            'Initialize an instance of the PdfTaggedContent class
            Dim taggedContent As PdfTaggedContent = New PdfTaggedContent(doc)

            'Set language and title for the document
            taggedContent.SetLanguage("en-US")
            taggedContent.SetTitle("Tagged PDF")

            'Set PDF/UA-1 compliance
            taggedContent.SetPdfUA1Identification()

            'Create font and brush
            Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Times New Roman", 14), True)
            Dim brush As PdfSolidBrush = New PdfSolidBrush(Color.Black)

            'Add a document element which is the root element of any structure tree
            Dim document As PdfStructureElement = taggedContent.StructureTreeRoot.AppendChildElement(PdfStandardStructTypes.Document)

            'Add a heading element
            Dim heading1 As PdfStructureElement = document.AppendChildElement(PdfStandardStructTypes.HeadingLevel1)
            heading1.BeginMarkedContent(page)
            Dim headingText = "What Is C#?"
            page.Canvas.DrawString(headingText, font, brush, New PointF(0, 0))
            heading1.EndMarkedContent(page)

            'Add a paragraph element 
            Dim paragraph As PdfStructureElement = document.AppendChildElement(PdfStandardStructTypes.Paragraph)
            paragraph.BeginMarkedContent(page)
            Dim paragraphText = "C# is pronounced C-Sharp. It is an object-oriented programming language created by Microsoft that runs on the.NET Framework." & "C# has roots from the C family, and the language is close to other popular languages like C++ and Java. The first version was released in year 2002." & "The latest version, C# 11, was released in November 2022. C# can be used for:"
            Dim rect As RectangleF = New RectangleF(0, 30, page.Canvas.ClientSize.Width, page.Canvas.ClientSize.Height)
            page.Canvas.DrawString(paragraphText, font, brush, rect)
            paragraph.EndMarkedContent(page)

            'Add an unordered list element
            Dim listElement As PdfStructureElement = document.AppendChildElement(PdfStandardStructTypes.List)
            listElement.BeginMarkedContent(page)
            Dim listContent = "Mobile applications" & vbLf & "Desktop applications" & vbLf & "Web applications" & vbLf & "Web services" & vbLf & "Web sites" & vbLf & "Games" & vbLf & "And many more!"
            Dim marker As PdfMarker = New PdfMarker(PdfUnorderedMarkerStyle.Asterisk)
            marker.Font = font
            Dim list As PdfList = New PdfList(listContent)
            list.Font = font
            list.Indent = 2
            list.TextIndent = 4
            list.Brush = brush
            list.Marker = marker
            list.Draw(page, 0, 100)
            listElement.EndMarkedContent(page)

            'Add a figure element
            Dim figure As PdfStructureElement = document.AppendChildElement(PdfStandardStructTypes.Figure)
            figure.BeginMarkedContent(page)
            Dim image As PdfImage = PdfImage.FromFile("Csharp.png")
            page.Canvas.DrawImage(image, New PointF(0, 230))
            figure.EndMarkedContent(page)

            'Add a table element
            Dim table As PdfStructureElement = document.AppendChildElement(PdfStandardStructTypes.Table)
            table.BeginMarkedContent(page)
            Dim pdfTable As PdfTable = New PdfTable()
            pdfTable.Style.DefaultStyle.Font = font
            Dim dataTable As DataTable = New DataTable()
            dataTable.Columns.Add("Year")
            dataTable.Columns.Add("Product")
            dataTable.Columns.Add("Sales")
            dataTable.Rows.Add(New String() {"2020", "Components", "$20,000"})
            dataTable.Rows.Add(New String() {"2021", "Bikes", "$6,300"})
            pdfTable.DataSource = dataTable
            pdfTable.Style.ShowHeader = True
            pdfTable.Draw(page.Canvas, New PointF(0, 320), 300F)
            table.EndMarkedContent(page)

            'Add a link element
            Dim link As PdfStructureElement = document.AppendChildElement(PdfStandardStructTypes.Link)
            link.BeginMarkedContent(page)
            Dim link2 As PdfTextWebLink = New PdfTextWebLink()
            link2.Text = "www.google.com"
            link2.Url = "https://www.google.com"
            link2.Font = font
            link2.Brush = brush
            link2.DrawTextWebLink(page.Canvas, New PointF(0, 390))
            link.EndMarkedContent(page)

            'Save the result document
            doc.SaveToFile("CreateTaggedPdf.pdf")
        End Sub
    End Class
End Namespace

The generated tagged PDF document:

Create tagged PDF in C# or VB.NET

C#/VB.NET: Count the Number of Sheets, Rows, Columns and Cells in Excel

In some cases, you may want to know the number of sheets in an Excel file or the number of used cells, rows and columns of a particular sheet in an Excel file. Counting them one by one manually by yourself is a time-consuming job, especially if you have numerous Excel files. To automate this feature, this article will introduce how to programmatically count the number of sheets, and used cells, rows and columns in Excel in C# and VB.NET using Spire.XLS for .NET API.

  • Count the Number of Sheets in an Excel File
  • Count the Number of Used Cells, Rows and Columns in an Excel Sheet

Installation

You can install Spire.XLS for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.XLS

Alternatively, you can also download the API from the official website and extract the package, then add the DLL files under the BIN folder to your project as references.

Count the Number of Sheets in an Excel File in C# and VB.NET

The following steps demonstrate how to count the number of sheets in an Excel file:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the number of sheets in the file through Workbook.Worksheets.Count property.

C#

using Spire.Xls;

namespace CountSheetsInExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Input.xlsx");

            //Get the number of sheets in the file
            int sheetCount = workbook.Worksheets.Count;
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace CountSheetsInExcel
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Workbook class
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Input.xlsx")

            'Get the number of sheets in the file
            Dim sheetCount As Integer = workbook.Worksheets.Count
        End Sub
    End Class
End Namespace

Count the Number of Used Cells, Rows and Columns in an Excel Sheet in C# and VB.NET

The following steps demonstrate how to count the number of used cells, rows and columns of a particular sheet in Excel:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a particular sheet by its index through Workbook.Worksheets[int] property.
  • Get the number of used rows in the sheet through Worksheet.Rows.Length property.
  • Get the number of used columns in the sheet through Worksheet.Columns.Length property.
  • Get the number of used cells in the sheet through Worksheet.Cells.Length property.

C#

using Spire.Xls;

namespace CountCellsRowsAndColumnsInExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Input.xlsx");

            //Get the first sheet by its index
            Worksheet sheet = workbook.Worksheets[0];

            //Get the number of rows in the sheet
            int rowCount = sheet.Rows.Length;
            //Get the number of columns in the sheet
            int colCount = sheet.Columns.Length;
            //Get the number of cells in the sheet
            int cellCount = sheet.Cells.Length;
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace CountCellsRowsAndColumnsInExcel
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Workbook class
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Input.xlsx")

            'Get the first sheet by its index
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Get the number of rows in the sheet
            Dim rowCount As Integer = sheet.Rows.Length
            'Get the number of columns in the sheet
            Dim colCount As Integer = sheet.Columns.Length
            'Get the number of cells in the sheet
            Dim cellCount As Integer = sheet.Cells.Length
        End Sub
    End Class
End Namespace
Design a site like this with WordPress.com
Get started