Thursday, 07 July 2022 08:46

C#/VB.NET: Convert CSV to PDF

CSV is one of the commonly used file formats for exchanging tabular data between applications. However, in some circumstances, CSV may not be the most appropriate file format. For instance, if you have a CSV report that needs to be sent to an important customer, the best way to ensure the file appears as-is on the customer's device is to convert it to PDF. This article will demonstrate how to convert CSV to PDF 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

Convert CSV to PDF in C# and VB.NET

The following are the steps to convert a CSV file to PDF:

  • Create an instance of Workbook class.
  • Load the CSV file using Workbook.LoadFromFile(filePath, separator) method.
  • Set the Workbook.ConverterSetting.SheetFitToPage property as true to ensure the worksheet is rendered to one PDF page.
  • Get the first worksheet in the Workbook using Workbook.Worksheets[0] property.
  • Loop through the columns in the worksheet and auto-fit the width of each column using Worksheet.AutoFitColumn() method.
  • Save the worksheet to PDF using Worksheet.SaveToPdf() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace ConvertCsvToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook wb = new Workbook();
            //Load a CSV file
            wb.LoadFromFile("Sample.csv", ",");

            //Set SheetFitToPage property as true to ensure the worksheet is converted to 1 PDF page
            wb.ConverterSetting.SheetFitToPage = true;

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

            //Loop through the columns in the worksheet
            for (int i = 1; i < sheet.Columns.Length; i++)
            {
                //AutoFit columns
                sheet.AutoFitColumn(i);
            }

            //Save the worksheet to PDF
            sheet.SaveToPdf("toPDF.pdf");
        }
    }
}

C#/VB.NET: Convert CSV to PDF

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.

Published in Conversion
Friday, 02 December 2022 08:12

C#/VB.NET: Convert Excel to SVG

SVG, short for Scalable Vector Graphics, is a web-friendly vector image format. SVG has many advantages over other image formats. One of the most significant advantages is resolution independence, which means you can resize SVG images as needed without losing image quality. Sometimes, you may need to convert Excel files to SVG for web viewing. This article will demonstrate how to programmatically convert Excel to SVG 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

Convert an Excel Worksheet to SVG using C# and VB.NET

Spire.XLS provides the Worksheet.SaveToSVGStream() method to convert an Excel worksheet to SVG. The detailed steps are as follows:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index through Workbook.Worksheets[int] property.
  • Initialize an instance of the FileStream class.
  • Save the worksheet to SVG using Worksheet.ToSVGStream(Stream, int, int, int, int) method.
  • C#
  • VB.NET
using Spire.Xls;
using System.IO;

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

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

            //Create an instance of FileStream class
            FileStream fs = new FileStream("E:\\Program Files\\WorksheetToSVG.svg", FileMode.Create);
            //Save the worksheet to SVG
            sheet.ToSVGStream(fs, 0, 0, 0, 0);
            fs.Flush();
            fs.Close();            
        }
    }
}

C#/VB.NET: Convert Excel to SVG

Convert an Excel Chart Sheet to SVG using C# and VB.NET

A chart sheet is a worksheet that only contains a chart. Spire.XLS allows you to convert a chart sheet to SVG by using the ChartSheet.ToSVGStream() method. The detailed steps are as follows:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific chart sheet by its index through Workbook.Chartsheets[int] property.
  • Initialize an instance of the FileStream class.
  • Save the chart sheet to SVG using ChartSheet.ToSVGStream(Stream) method.
  • C#
  • VB.NET
using Spire.Xls;
using System.IO;

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

            //Get the first chart sheet
            ChartSheet chartSheet = workbook.Chartsheets[0];

            //Create an instance of FileStream class
            FileStream fs = new FileStream("E:\\ProgramFiles\\ChartSheetToSVG.svg", FileMode.Create);
            //Save the chart sheet to SVG
            chartSheet.ToSVGStream(fs);
            fs.Flush();
            fs.Close();
        }
    }
}

C#/VB.NET: Convert Excel to SVG

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.

Published in Conversion
Monday, 16 December 2024 03:17

C#: Convert Excel to ODS or ODS to Excel

Excel, developed by Microsoft, is a widely used spreadsheet application that offers a range of features for data analysis, visualization, and management. ODS (OpenDocument Spreadsheet), on the other hand, is an open standard format for spreadsheets, which means it can be read and edited by various software applications, including LibreOffice and Apache OpenOffice.

Converting between these two formats can be necessary for compatibility, sharing, or specific feature requirements. In this article, you will learn how to convert Excel to ODS or OSD to Excel in C# 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

Convert Excel to ODS (OpenDocument Spreadsheet) in C#

You can load an Excel (.xls or .xlsx) file and then save it as an ODS file through the Workbook.SaveToFile(string fileName, FileFormat.ODS) method. The following are the detailed steps:

  • Create a Workbook instance.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Save the Excel file to ODS format using Workbook.SaveToFile(string fileName, FileFormat.ODS) method.
  • C#
using Spire.Xls;

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

            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

            // Save the Excel to ODS file
            workbook.SaveToFile("ToODS.ods", FileFormat.ODS);
        }
    }
}

Convert an Excel file to an ODS file

Convert ODS to Excel (XLS/XLSX) in C#

Spire.XLS for .NET also supports converting an ODS file back to Excel XLS or XLS format. The following are the detailed steps:

  • Create a Workbook instance.
  • Load an ODS file using Workbook.LoadFromFile() method.
  • Save the ODS file in XLS or XLSX format using Workbook.SaveToFile(string fileName, FileFormat fileFormat) method.
  • C#
using Spire.Xls;

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

            // Load an ODS file
            workbook.LoadFromFile("ToODS.ods");

            // Save the ODS file in XLSX format
            workbook.SaveToFile("ToExcel.xlsx", FileFormat.Version2016);

            // Save the ODS file in XLS format
            workbook.SaveToFile("ToExcel.xls", FileFormat.Version97to2003);
        }
    }
}

The output XLS and XLSX files converted from an ODS file

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.

Published in Conversion

If you're creating a written report on a company's monthly expenditures, you might need to include a spreadsheet to show the financial figures and make them easier to read. This article demonstrates how to convert Excel data into a Word table maintaining the formatting in C# and VB.NET using Spire.Office for .NET.

Install Spire.Office for .NET

To begin with, you need to add the DLL files included in the Spire.Office 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.Office

Export Excel Data to a Word Table with Formatting

Below are the steps to convert Excel data to a Word table and keep the formatting using Spire.Office for .NET.

  • Create a Workbook object and load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Create a Document object, and add a section to it.
  • Add a table using Section.AddTable() method.
  • Detect the merged cells in the worksheet and merge the corresponding cells of the Word tale using the custom method MergeCells().
  • Get value of a specific Excel cell through CellRange.Value property and add it to a cell of the Word table using TableCell.AddParagraph().AppendText() method.
  • Copy the font style and cell style from Excel to the Word table using the custom method CopyStyle().
  • Save the document to a Word file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;

namespace ConvertExcelToWord
{
    internal class Program
    {
        static void Main(string[] args)
        {

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

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

            //Create a Word document
            Document doc = new Document();
            Section section = doc.AddSection();
            section.PageSetup.Orientation = PageOrientation.Landscape;

            //Add a table
            Table table = section.AddTable(true);
            table.ResetCells(sheet.LastRow, sheet.LastColumn);

            //Merge cells
            MergeCells(sheet, table);

            for (int r = 1; r <= sheet.LastRow; r++)
            {
                //Set row Height
                table.Rows[r - 1].Height = (float)sheet.Rows[r - 1].RowHeight;

                for (int c = 1; c <= sheet.LastColumn; c++)
                {
                    CellRange xCell = sheet.Range[r, c];
                    TableCell wCell = table.Rows[r - 1].Cells[c - 1];

                    //Export data from Excel to Word table
                    TextRange textRange = wCell.AddParagraph().AppendText(xCell.NumberText);

                    //Copy font and cell style from Excel to Word
                    CopyStyle(textRange, xCell, wCell);
                }
            }

            //Save the document to a Word file
            doc.SaveToFile("ExportToWord.docx", Spire.Doc.FileFormat.Docx);
        }
        //Merge cells if any
        private static void MergeCells(Worksheet sheet, Table table)
        {
            if (sheet.HasMergedCells)
            {
                //Get merged cell ranges from Excel
                CellRange[] ranges = sheet.MergedCells;

                //Merge corresponding cells in Word table
                for (int i = 0; i < ranges.Length; i++)
                {
                    int startRow = ranges[i].Row;
                    int startColumn = ranges[i].Column;
                    int rowCount = ranges[i].RowCount;
                    int columnCount = ranges[i].ColumnCount;
                    if (rowCount > 1 && columnCount > 1)
                    {
                        for (int j = startRow; j <= startRow + rowCount; j++)
                        {
                            table.ApplyHorizontalMerge(j - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
                        }
                        table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount -1);
                    }
                    if (rowCount > 1 && columnCount == 1)
                    {
                        table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount -1);
                    }
                    if (columnCount > 1 && rowCount == 1)
                    {
                        table.ApplyHorizontalMerge(startRow - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
                    }
                }
            }
        }

        //Copy cell style of Excel to Word table
        private static void CopyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell)
        {
            //Copy font style
            wTextRange.CharacterFormat.TextColor = xCell.Style.Font.Color;
            wTextRange.CharacterFormat.FontSize = (float)xCell.Style.Font.Size;
            wTextRange.CharacterFormat.FontName = xCell.Style.Font.FontName;
            wTextRange.CharacterFormat.Bold = xCell.Style.Font.IsBold;
            wTextRange.CharacterFormat.Italic = xCell.Style.Font.IsItalic;
            //Copy backcolor
            wCell.CellFormat.BackColor = xCell.Style.Color;
            //Copy horizontal alignment
            switch (xCell.HorizontalAlignment)
            {
                case HorizontalAlignType.Left:
                    wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
                    break;
                case HorizontalAlignType.Center:
                    wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
                    break;
                case HorizontalAlignType.Right:
                    wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
                    break;
            }
            //Copy vertical alignment
            switch (xCell.VerticalAlignment)
            {
                case VerticalAlignType.Bottom:
                    wCell.CellFormat.VerticalAlignment = VerticalAlignment.Bottom;
                    break;
                case VerticalAlignType.Center:
                    wCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    break;
                case VerticalAlignType.Top:
                    wCell.CellFormat.VerticalAlignment = VerticalAlignment.Top;
                    break;
            }
        }
    }
}

C#/VB.NET: Convert Excel Data to Word Tables with Formatting

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.

Published in Conversion
Friday, 04 March 2016 07:26

Convert worksheet to PDF in C#, VB.NET

We have discussed before about converting workbook to PDF. However, in this section, we will show you a neat solution to convert the specific worksheet to PDF with C# and VB.NET in workbook. Apply Spire.Xls for .NET in your application and you can turn worksheet into PDF easily without changing the layout of worksheet.

In the following sections, we will demonstrate how to convert worksheet to PDF.

Step 1: Initialize a new instance of Workbook class and load the sample Excel file.

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

Step 2: Get its first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Convert the selected worksheet to PDF and save to file.

sheet.SaveToPdf("toPDF.pdf");

Step 4: Launch the file.

System.Diagnostics.Process.Start("toPDF.pdf");

Effective screenshot:

Convert worksheet to PDF in C#, VB.NET

Full codes:

[C#]
using Spire.Xls;

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

            Worksheet sheet = workbook.Worksheets[0];

            sheet.SaveToPdf("toPDF.pdf");
            System.Diagnostics.Process.Start("toPDF.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace Excel_Worksheet_to_PDF
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("Sample.xlsx")

			Dim sheet As Worksheet = workbook.Worksheets(0)

			sheet.SaveToPdf("toPDF.pdf")
			System.Diagnostics.Process.Start("toPDF.pdf")
		End Sub
	End Class
End Namespace
Published in Conversion

This article shows how to display formula and its result separately when converting excel to database via Spire.XLS. This demo uses an Excel file with formula in it and show the conversion result in a Windows Forms Application project.

Screenshot of the test excel file:

Show formula and its result separately when converting excel to datatable in C#

Here are the detailed steps:

Steps 1: Create a Windows Forms Application in Visual Studio.

Steps 2: Drag a DataGridView and two Buttons from Toolbox to the Form and change names of the buttons as Formula and Result to distinguish.

Show formula and its result separately when converting excel to datatable in C#

Steps 3: Double click Button formula and add the following code.

3.1 Load test file and get the first sheet.

Workbook workbook = new Workbook();
workbook.LoadFromFile(@"1.xlsx");
Worksheet sheet = workbook.Worksheets[0];

3.2 Invoke method ExportDataTable of the sheet and output data range. Parameters of ExportDataTable are range to export, indicates if export column name and indicates whether compute formula value, then it will return exported datatable.

Description of ExportDataTable:

public DataTable ExportDataTable(CellRange range, bool exportColumnNames, bool computedFormulaValue);

Code:

DataTable dt = sheet.ExportDataTable(sheet.AllocatedRange, false, false);

3.3 Show in DataGridView

this.dataGridView1.DataSource = dt; 

Steps 4: Do ditto to Button Result. Only alter parameter computedFormulaValue as true.

Workbook workbook = new Workbook();
workbook.LoadFromFile(@"1.xlsx");
Worksheet sheet = workbook.Worksheets[0];
DataTable dt = sheet.ExportDataTable(sheet.AllocatedRange, false, true);
this.dataGridView1.DataSource = dt; 

Steps 5: Start the project and check the result.

Show formula and its result separately when converting excel to datatable in C#

Button code here:

//Formula
private void button1_Click(object sender, EventArgs e)
{
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"1.xlsx");
Worksheet sheet = workbook.Worksheets[0];
DataTable dt = sheet.ExportDataTable(sheet.AllocatedRange, false, false);
this.dataGridView1.DataSource = dt;

}
//Result
private void button2_Click(object sender, EventArgs e)
{
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"1.xlsx");
Worksheet sheet = workbook.Worksheets[0];
DataTable dt = sheet.ExportDataTable(sheet.AllocatedRange, false, true);
this.dataGridView1.DataSource = dt;
}
Published in Conversion

Spire.XLS has powerful functions to export Excel worksheets into different image file formats. In the previous articles, we have already shown you how to convert Excel worksheets into BMP, PNG, GIF, JPG, JPEG, TIFF. Now Spire.XLS newly starts to support exporting Excel worksheet into EMF image. With the help of Spire.XLS, you only need three lines of codes to finish the conversion function.

Make sure Spire.XLS (Version 7.6.43 or above) has been installed correctly and then add Spire.xls.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Xls\Bin\NET4.0\ Spire. Xls.dll". Here comes to the details of how to convert excel worksheet to EMF image.

Step 1: Create an excel document and load the document from file.

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

Step 2: Get the first worksheet in excel workbook.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Save excel worksheet into EMF image.

sheet.SaveToEMFImage("result.emf", 1, 1, 19, 6, system.Drawing.Imaging.EmfType.EmfPlusDual);

Effective screenshot:

How to convert Excel worksheet to EMF image in C#

Full codes:

using Spire.Xls;

namespace XLStoEMF
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("XLS2.xlsx");
            
            Worksheet sheet = workbook.Worksheets[0];
            sheet.SaveToEMFImage("result.emf", 1, 1, 19,6, System.Drawing.Imaging.EmfType.EmfPlusDual);
            
         }
    }
}
Published in Conversion

Using Spire.XLS, programmers are able to save the whole worksheet as PDF by calling the method SaveToPdf(). However, you may only want to save or export a part of worksheet as PDF. Since Spire.XLS doesn't provide a method to directly convert a range of cells to PDF, we can copy the selected ranges to a new worksheet and then save it as PDF file. This method seems complex, but it is still efficient with Spire.XLS.

Look at the test file below, we only want the cells from A1 to H11 converted as PDF. We will firstly create a new blank worksheet, copy the selected range to the new sheet using CellRange.Copy() method, then convert the new sheet as PDF.

How to Convert Selected Range of Cells to PDF in C#, VB.NET

Code Snippet:

Step 1: Create a new workbook and load the test file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("test.xlsx", ExcelVersion.Version2010);

Step 2: Add a new worksheet to workbook.

workbook.Worksheets.Add("newsheet");

Step 3: Copy the selected range from where it stores to the new worksheet.

workbook.Worksheets[0].Range["A1:H11"].Copy(workbook.Worksheets[1].Range["A1:H11"]);

Step 4: Convert the new worksheet to PDF.

workbook.Worksheets[1].SaveToPdf("result.pdf", Spire.Xls.FileFormat.PDF);

Result:

How to Convert Selected Range of Cells to PDF in C#, VB.NET

Full Code:

[C#]
using Spire.Xls;
namespace Convert
{
    class Program
    {
          static void Main(string[] args)
{
    Workbook workbook = new Workbook();
    workbook.LoadFromFile("test.xlsx", ExcelVersion.Version2010);
    // add a new sheet to workbook
    workbook.Worksheets.Add("newsheet");
    //Copy your area to new sheet.
    workbook.Worksheets[0].Range["A1:H11"].Copy(workbook.Worksheets[1].Range["A1:H11"]);
    //convert new sheet to pdf
    workbook.Worksheets[1].SaveToPdf("result.pdf", Spire.Xls.FileFormat.PDF);

}

        }
    }
[VB.NET]
Imports Spire.Xls
Namespace Convert
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("test.xlsx", ExcelVersion.Version2010)
			' add a new sheet to workbook
			workbook.Worksheets.Add("newsheet")
			'Copy your area to new sheet.
			workbook.Worksheets(0).Range("A1:H11").Copy(workbook.Worksheets(1).Range("A1:H11"))
			'convert new sheet to pdf
			workbook.Worksheets(1).SaveToPdf("result.pdf", Spire.Xls.FileFormat.PDF)

		End Sub

	End Class
End Namespace
Published in Conversion

A file with the XLSM extension is an Excel Macro-Enabled Workbook file. For security reasons, XLS file or XLSX file does not enable macros by default. Thus, if you want to execute macros in Excel file, you need to convert XLS or XLSX to XLSM at the first place. In this article, I’ll introduce you how to convert XLS to XLSM with the macro maintained using Spire.XLS.

Here is the method:

Step 1: Create a new instance of Spire.Xls.Workbook class.

Workbook workbook = new Workbook();

Step 2: Load the test file and imports its data to workbook.

workbook.LoadFromFile("test.xls", ExcelVersion.Version97to2003);

Step 3: Save the workbook as a new XLSM file.

workbook.SaveToFile("result.xlsm", FileFormat.Version2007);

Full Code:

[C#]
using Spire.Xls;
namespace Convert
{
    class Program
    {
          static void Main(string[] args)
{
    Workbook workbook = new Workbook();
    workbook.LoadFromFile("test.xls", ExcelVersion.Version97to2003);
    workbook.SaveToFile("result.xlsm", FileFormat.Version2007);
}

        }
    }
[VB.NET]
Imports Spire.Xls
Namespace Convert
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("test.xls", ExcelVersion.Version97to2003)
			workbook.SaveToFile("result.xlsm", FileFormat.Version2007)
		End Sub

	End Class
End Namespace

Test File:

As is shown in the picture, Excel automatically disables macro in XLS file.

Convert XLS to XLSM and Maintain Macro in C#, VB.NET

Result:

No security warning in the converted XLSM file.

Convert XLS to XLSM and Maintain Macro in C#, VB.NET

Published in Conversion
Friday, 26 August 2022 08:43

C#/VB.NET: Convert Excel to XPS

XPS (XML Paper Specification) is a specification for a page description language and a fixed-document format developed by Microsoft. It defines the layout of a document and the visual appearance of each page. Sometimes you may need to convert an Excel document to XPS for distribution, archiving or printing purposes, and this article will demonstrate how to accomplish this task programmatically 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

Convert Excel to XPS

Spire.XLS for .NET allows you to convert Excel (.xls/ .xlsx) to XPS with only three lines of code. The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.LoadFromFile() method.
  • Convert the Excel document to XPS using Workbook.SaveToFile(String, FileFormat) method.
  • C#
  • VB.NET
using Spire.Xls;

namespace ExceltoXPS
{
    class Program
    {
        static void Main(string[] args)
        {

            //Create a Workbook object.
            Workbook workbook = new Workbook();

            //Load a sample Excel document
            workbook.LoadFromFile(@"E:\Files\\sample0.xlsx", ExcelVersion.Version2010);

            //Convert the document to XPS
            workbook.SaveToFile("result.xps", FileFormat.XPS);
        }
    }
}

C#/VB.NET: Convert Excel to XPS

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.

Published in Conversion
Page 2 of 3