When we print Word and PDF documents which have regular page size, we can clearly know the pagination information for Word and PDF by delimiters. Excel document is different since Excel pagination is based on its content when we print Excel document or convert to Pdf. So get Excel pagination information is important to developer. Below would introduce a solution to get pagination information in Excel document.

The solution call book.GetSplitPageInfo() method to obtain information of excel document and return this information to the List<Dictionary<int, PageColRow>> object via Spire.XLS. By the object we can get this information about: sheet count, page count and the start and end column and row of every page in excel document. Below is effect screenshots:

Get information of pagination in Excel document

The main steps of the solution are:

Step 1: Create and load an excel document.

Workbook book = new Workbook();
book.LoadFromFile(@"test.xlsx");

Step 2: Call GetSplitPageInfo() method to Excel information.

List> pageInfoList = book.GetSplitPageInfo();

Get information of pagination in Excel document

The full code:

[C#]
using System.Collections.Generic;
using Spire.Xls;
using Spire.Xls.Core.Converter.Exporting.EMF;
namespace GetPageInformation
{
    class Program
    {
        static void Main(string[] args)
        {
            // create and load Excel document
Workbook book = new Workbook();
            book.LoadFromFile(@"test.xlsx");
           // get the Excel document information and save in pageInfoList object
            List> pageInfoList = book.GetSplitPageInfo();

            // the sheet count of excel 
            int sheetCount = pageInfoList.Count;

            //The page count of the first sheet
            int pageCount = pageInfoList[0].Count;
            book.SaveToFile("result.pdf", FileFormat.PDF);
        }
    }
}
[VB.NET]
Imports System.Collections.Generic
Imports Spire.Xls
Imports Spire.Xls.Core.Converter.Exporting.EMF
Module Module1

Sub Main()
'create and load Excel document
        Dim book As New Workbook()
        book.LoadFromFile("test.xlsx")
' get the Excel document information and save in pageInfoList object
        Dim pageInfoList As List(Of Dictionary(Of Integer, PageColRow)) = book.GetSplitPageInfo()

        ' the sheet count of excel 
        Dim sheetCount As Integer = pageInfoList.Count

        'The page count of the first sheet
        Dim pageCount As Integer = pageInfoList(0).Count
        book.SaveToFile("result.pdf", FileFormat.PDF)
    End Sub

End Module
Published in Document Operation
Tuesday, 22 November 2022 08:17

C#/VB.NET: Print Excel Documents

Excel documents are easy to print, but it would be a bit tricky if you have some special printing requirements. For example, printing only selected range of a sheet, repeating the header row on each page, or fitting a worksheet on one page. This article covers how to set Excel print options via page setup and how to send an Excel document to printer in C# and VB.NET by 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

Set Excel Print Options via Page Setup in C# and VB.NET

Excel Page Setup provides options to control how a worksheet will be printed, such as whether to print comments, whether to print gridlines and specify the cell range to print. Spire.XLS offers the PageSetup object to deal with these things. The following are the steps to set Excel print options through PageSetup 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.
  • Get PageSetup object through Worksheet.PageSetup property.
  • Set page margins, print area, pint title row, print quality, etc. through the properties under PageSetup object.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

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

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

            //Get the PageSetup object of the first worksheet
            PageSetup pageSetup = worksheet.PageSetup;

            //Set page margins
            pageSetup.TopMargin = 0.3;
            pageSetup.BottomMargin = 0.3;
            pageSetup.LeftMargin = 0.3;
            pageSetup.RightMargin = 0.3;

            //Specify print area
            pageSetup.PrintArea = "A1:D10";

            //Specify title row
            pageSetup.PrintTitleRows = "$1:$2";

            //Allow to print with row/column headings
            pageSetup.IsPrintHeadings = true;

            //Allow to print with gridlines
            pageSetup.IsPrintGridlines = true;

            //Allow to print comments as displayed on worksheet
            pageSetup.PrintComments = PrintCommentType.InPlace;

            //Set printing quality (dpi)
            pageSetup.PrintQuality = 300;

            //Allow to print worksheet in black & white mode
            pageSetup.BlackAndWhite = true;

            //Set the printing order
            pageSetup.Order = OrderType.OverThenDown;

            //Fit worksheet on one page
            pageSetup.IsFitToPage = true;

            //Save the workbook
            workbook.SaveToFile("PagePrintOptions.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Print Excel Documents

Print Excel Documents Using Print Dialog in C# and VB.NET

A Print Dialog box lets users to select options for a particular print job. For example, the user can specify the printer to use. The following are the steps to send an Excel document to a print dialog using Spire.XLS for .NET.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Create a PrintDialog object.
  • Specify printer settings through the properties under PrintDialog object.
  • Apply the print dialog to workbook.
  • Get PrintDocument object from the workbook through Workbook.PrintDocument property.
  • Invoke the print dialog and start printing using PrintDocument.Print() method.
  • C#
  • VB.NET
using System;
using Spire.Xls;
using System.Drawing.Printing;
using System.Windows.Forms;

namespace PrintExcelUsingPrintDialog
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

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

            //Fit worksheet on one page    
            PageSetup pageSetup = workbook.Worksheets[0].PageSetup;
            pageSetup.IsFitToPage = true;

            //Create a PrintDialog object
            PrintDialog dialog = new PrintDialog();

            //Specify printer settings 
            dialog.AllowCurrentPage = true;
            dialog.AllowSomePages = true;
            dialog.AllowSelection = true;
            dialog.UseEXDialog = true;
            dialog.PrinterSettings.Duplex = Duplex.Simplex;

            //Apply the dialog to workbook 
            workbook.PrintDialog = dialog;

            //Create a PrintDocument object based on the workbook
            PrintDocument printDocument = workbook.PrintDocument;

            //Invoke the print dialog
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                printDocument.Print();
            }
        }
    }
}

C#/VB.NET: Print Excel Documents

Silently Print Excel Documents in C# and VB.NET

If you do not want to see the print dialog or the print process, you can silently print Excel documents to a specified printer. The following are the steps.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Set the print controller to StandardPrintController, which will prevent print process from showing.
  • Get PrinterSettings object from the workbook through Workbook.PrintDocument.PrinterSettings property.
  • Specify printer name, duplex mode and print pages through the properties under PrinerSettings object.
  • Print the workbook using Workbook.PrintDocument.Print() method.
  • C#
  • VB.NET
using Spire.Xls;
using System.Drawing.Printing;

namespace SilentlyPrint
{
    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");

            //Fit worksheet on one page    
            PageSetup pageSetup = workbook.Worksheets[0].PageSetup;
            pageSetup.IsFitToPage = true;

            //Set the print controller to StandardPrintController, which will prevent print process from showing
            workbook.PrintDocument.PrintController = new StandardPrintController();

            //Get PrinterSettings from the workbook
            PrinterSettings settings = workbook.PrintDocument.PrinterSettings;

            //Specify printer name, duplex mode and print pages
            settings.PrinterName = "HP LaserJet P1007"; 
            settings.Duplex = Duplex.Simplex;
            settings.FromPage = 1;
            settings.ToPage = 3;         

            //Print the workbook
            workbook.PrintDocument.Print();
        }
    }
}

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 Print

This article reveals using Spire.XLS for .NET to create a new Excel file dynamically and save it to stream. Alternatively, loading Excel file from stream in C# will also be fully described in this article as an additional function of Spire.XLS for .NET.

First we need to complete the preparatory work:

  • Download the latest Spire.XLS and install it on your machine.
  • Add the Spire.XLS.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.

Here comes to the explanation of the code:

Dynamically create Excel file and save it to stream

Firstly you can initiate an object of Spire.XLS.workbook

Workbook wbToStream= new Workbook();

Add Spire.XlS.Worksheet object by using the WorkSheet properties of Spire.XlS.Workbook. After that, write text in cell by take advantage of Range properties of Worksheet.

Worksheet sheet = wbFromStream.Worksheets[0];
sheet.Range["C10"].Text = "The sample demonstrates how to save an Excel workbook to stream.";

Then call the method SaveToStream of the Spire.XLS.Workbook object and save all the data which is in XLS format to stream.

wbToStream.SaveToStream(file_stream);

Let’s preview the sample Excel:

save to stream

Load Excel file from stream in C#

You can initiate an object of Spire.Xls.Workbook

Workbook wbFromStream = new Workbook();

Load data which is in .xls format from steam by calling the method "LoadFromStream" of the Spire.XLS.Workbook object.

wbFromStream.LoadFromStream(fileStream);

Save the object of Spire.XLS.Workbook as an .xls file.

wbFromStream.SaveToFile("From_stream.xls",ExcelVersion.Version97to2003);

Look at this screenshot:

save to stream

And what below is the full code used in the two functions:

static void Main(string[] args)
{
 //A: Dynamically create Excel file and save it to stream
 Workbook wbToStream= new Workbook();
 Worksheet sheet = wbToStream.Worksheets[0];
 sheet.Range["C10"].Text = "The sample demonstrates how to save an Excel workbook to stream.";
 FileStream file_stream = new FileStream("To_stream.xls", FileMode.Create);
 wbToStream.SaveToStream(file_stream);        
 file_stream.Close();
 System.Diagnostics.Process.Start("To_stream.xls");
            
//B. Load Excel file from stream
 Workbook wbFromStream = new Workbook();
 FileStream fileStream = File.OpenRead("sample.xls");
 fileStream.Seek(0, SeekOrigin.Begin);
 wbFromStream.LoadFromStream(fileStream);
 wbFromStream.SaveToFile("From_stream.xls",ExcelVersion.Version97to2003);
 fileStream.Dispose();
 System.Diagnostics.Process.Start("From_stream.xls");
}
Published in Document Operation
Wednesday, 15 February 2023 05:20

C#/VB.NET: Add Document Properties in Excel

Document properties, also known as metadata, are a set of data that describe a document. In Excel, you can add built-in document properties such as author, title, and keywords to quickly locate and identify documents in a folder. Or you can also add custom properties to provide more information about the Excel document. In this article, you will learn how to programmatically add built-in and custom document properties to an Excel document 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

Add Built-in Document Properties in Excel in C# and VB.NET

Built-in document properties are basic information about a document such as title, subject, author, category, etc. The names of these properties are predefined that cannot be edited, but Spire.XLS for .NET allows you to set specific values for these properties. The following are the detailed steps.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.LoadFromFile() method.
  • Get the built-in document properties of the document using Workbook.DocumentProperties property.
  • Set specific document properties such as title, author, keywords and comments using the properties of BuiltInDocumentProperties class.
  • Save the result document using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

            //Load a sample Excel document
            workbook.LoadFromFile("sample.xlsx");

            //Set built-in document properties for the Excel workbook
            workbook.DocumentProperties.Author = "E-iceblue Team";
            workbook.DocumentProperties.Title = "Add Built-in Document Properties in Excel ";
            workbook.DocumentProperties.Keywords = "Excel, Document Properties, C#, VB.NET";
            workbook.DocumentProperties.Category = "Spire.XLS Demo";
            workbook.DocumentProperties.Company = "E-iceblue";
            workbook.DocumentProperties.Comments = "Document properties are details about a file that describe or identify it.";

            //Save the result document
            workbook.SaveToFile("ExcelProperties.xlsx", FileFormat.Version2013);
        }
    }
}

C#/VB.NET: Add Document Properties in Excel

Add Custom Document Properties in Excel in C# and VB.NET

Custom document properties are additional properties that you can define for an Excel document. Spire.XLS for .NET allows you to add custom properties with specified names and values using ICustomDocumentProperties.Add() method. The following are the detailed steps.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.LoadFromFile() method.
  • Get the custom document properties of the document using Workbook.CustomDocumentProperties property.
  • Add custom document properties with different data types to the document using ICustomDocumentProperties.Add() method.
  • Save the result document using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;
using System;

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

            //Load a sample Excel document
            workbook.LoadFromFile("sample.xlsx");

            //Add custom document properties to the document
            workbook.CustomDocumentProperties.Add("_MarkAsFinal", true);
            workbook.CustomDocumentProperties.Add("The Editor", "E-iceblue");
            workbook.CustomDocumentProperties.Add("Phone Number", 12345678);
            workbook.CustomDocumentProperties.Add("Document ID", 1);
            workbook.CustomDocumentProperties.Add("Revision Date", DateTime.Now);

            //Save the result document
            workbook.SaveToFile("ExcelCustomProperties.xlsx", FileFormat.Version2013);
        }
    }
}

C#/VB.NET: Add Document Properties 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.

Published in Document Operation
Monday, 19 March 2012 06:55

C#/VB.NET: Merge Excel Files into One

Sometimes, we may get annoyed when we have to open many Excel files simultaneously. Merging Excel files of the same type or category can help us avoid the trouble and save us much time. This article will demonstrate how to merge Excel files into One in C# and VB.NET using 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

Merge Multiple Excel Workbooks into One in C# and VB.NET

The following are the steps to merge multiple Excel workbooks into one:

  • Create a string array from the Excel file paths.
  • Initialize a Workbook object to create a new Excel workbook, and clear the default worksheets in the workbook using Workbook.Worksheets.Clear() method.
  • Initialize another temporary Workbook object.
  • Loop through the string array, load the current workbook into the temporary Workbook object using Workbook.LoadFromFile() method.
  • loop through the worksheets in the current workbook, then copy each worksheet from the current workbook to the new workbook using Workbook.Worksheets.AddCopy() method.
  • Save the new workbook to file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace MergeExcelFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a string array from Excel file paths
            string[] inputFiles = new string[] { "April.xlsx", "May.xlsx", "June.xlsx" };

            //Initialize a new Workbook object
            Workbook newWorkbook = new Workbook();
            //Clear the default worksheets
            newWorkbook.Worksheets.Clear();

            //Initialize another temporary Workbook object
            Workbook tempWorkbook = new Workbook();

            //Loop through the string array
            foreach (string file in inputFiles)
            {
                //Load the current workbook
                tempWorkbook.LoadFromFile(file);
                //Loop through the worksheets in the current workbook
                foreach (Worksheet sheet in tempWorkbook.Worksheets)
                {
                    //Copy each worksheet from the current workbook to the new workbook
                    newWorkbook.Worksheets.AddCopy(sheet, WorksheetCopyType.CopyAll);
                }
            }

            //Save the new workbook to file
            newWorkbook.SaveToFile("MergeWorkbooks.xlsx", ExcelVersion.Version2013);
        }
    }
}

The input Excel workbooks:

C#/VB.NET: Merge Excel Files into One

The merged Excel workbook:

C#/VB.NET: Merge Excel Files into One

Merge Multiple Excel Worksheets into One in C# and VB.NET

We can merge multiple worksheets in the same or different workbooks into one. The following steps show how to merge two Excel worksheets in the same workbook into a single worksheet:

  • Initialize a Workbook object and load an Excel file using Workbook.LoadFromFile() method.
  • Get the two worksheets that need to be merged using Workbook.Worksheets[sheetIndex] property. Note the sheet index is zero-based.
  • Get the used range of the second worksheet using Worksheet.AllocatedRange property.
  • Specify the destination range in the first worksheet using Worksheet.Range[rowIndex, columnIndex] property. Note the row and column indexes are 1-based.
  • Copy the used range of the second worksheet to the destination range in the first worksheet using CellRange.Copy(destRange) method.
  • Remove the second worksheet using XlsWorksheet.Remove() method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace MergeExcelWorksheets
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

            //Get the first worksheet
            Worksheet sheet1 = workbook.Worksheets[0];
            //Get the second worksheet
            Worksheet sheet2 = workbook.Worksheets[1];

            //Get the used range in the second worksheet
            CellRange sourceRange = sheet2.AllocatedRange;
            //Specify the destination range in the first worksheet
            CellRange destRange = sheet1.Range[sheet1.LastRow + 1, 1];

            //Copy the used range of the second worksheet to the destination range in the first worksheet
            sourceRange.Copy(destRange);

            //Remove the second worksheet
            sheet2.Remove();

            //Save the result file
            workbook.SaveToFile("MergeWorksheets.xlsx", ExcelVersion.Version2013);
        }
    }
}

The input Excel worksheets:

C#/VB.NET: Merge Excel Files into One

The merged Excel worksheets:

C#/VB.NET: Merge Excel Files into One

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 Document Operation

Excel spreadsheet is a widely used file format that enables users to organize, analyze, and present data in a tabular format. The ability to interact with Excel files programmatically is highly valuable, as it allows automation and integration of Excel functionality into software applications. This capability is particularly useful when working with large datasets, performing complex calculations, or when data needs to be dynamically generated or updated. In this article, you will learn how to create, read, or update Excel documents 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

Create an Excel File in C#, VB.NET

Spire.XLS for .NET offers a variety of classes and interfaces that you can use to create and edit Excel documents. Here is a list of important classes, properties and methods involved in this article.

Member Description
Workbook class Represents an Excel workbook model.
Workbook.Worksheets.Add() method Adds a worksheet to workbook.
Workbook.SaveToFile() method Saves the workbook to an Excel document.
Worksheet class Represents a worksheet in a workbook.
Worksheet.Range property Gets a specific cell or cell range from worksheet.
Worksheet.Range.Value property Gets or sets the value of a cell.
Worksheet.Rows property Gets a collection of rows in worksheet.
Worksheet.InsertDataTable() method Imports data from DataTable to worksheet.
CellRange class Represents a cell or cell range in worksheet.

The following are the steps to create an Excel document from scratch using Spire.XLS for .NET.

  • Create a Workbook object.
  • Add a worksheet using Workbook.Worksheets.Add() method.
  • Write data to a specific cell through Worksheet.Range.Value property.
  • Import data from a DataTable to the worksheet using Worksheet.InsertDataTable() method.
  • Save the workbook to an Excel document using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;
using System.Data;

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

            //Remove default worksheets
            wb.Worksheets.Clear();

            //Add a worksheet and name it "Employee"
            Worksheet sheet = wb.Worksheets.Add("Employee");

            //Merge the cells between A1 and G1
            sheet.Range["A1:G1"].Merge();

            //Write data to A1 and apply formatting to it
            sheet.Range["A1"].Value = "Basic Information of Employees of Huanyu Automobile Company";
            sheet.Range["A1"].HorizontalAlignment = HorizontalAlignType.Center;
            sheet.Range["A1"].VerticalAlignment = VerticalAlignType.Center;
            sheet.Range["A1"].Style.Font.IsBold = true;
            sheet.Range["A1"].Style.Font.Size = 13F;

            //Set row height of the first row
            sheet.Rows[0].RowHeight = 30F;

            //Create a DataTable
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Gender");
            dt.Columns.Add("Birth Date");
            dt.Columns.Add("Educational Background");
            dt.Columns.Add("Contact Number");
            dt.Columns.Add("Position");
            dt.Columns.Add("ID");
            dt.Rows.Add("Allen", "Male", "1990-02-10", "Bachelor", "24756854", "Mechanic", "0021");
            dt.Rows.Add("Patrick", "Male", "1985-06-08", "Master", "59863247", "Mechanic", "0022");
            dt.Rows.Add("Jenna", "Female", "1989-11-25", "Bachelor", "79540352", "Sales", "0023");
            dt.Rows.Add("Tommy", "Male", "1988-04-16", "Master", "52014060", "Mechanic", "0024");
            dt.Rows.Add("Christina", "Female", "1998-01-21", "Bachelor", "35401489", "HR", "0025");

            //Import data from DataTable to worksheet
            sheet.InsertDataTable(dt, true, 2, 1, true);

            //Set row height of a range
            sheet.Range["A2:G7"].RowHeight = 15F;

            //Set column width 
            sheet.Range["A2:G7"].Columns[2].ColumnWidth = 15F;
            sheet.Range["A2:G7"].Columns[3].ColumnWidth = 21F;
            sheet.Range["A2:G7"].Columns[4].ColumnWidth = 15F;

            //Set border style of a range
            sheet.Range["A2:G7"].BorderAround(LineStyleType.Medium);
            sheet.Range["A2:G7"].BorderInside(LineStyleType.Thin);
            sheet.Range["A2:G2"].BorderAround(LineStyleType.Medium);
            sheet.Range["A2:G7"].Borders.KnownColor = ExcelColors.Black;

            //Save to a .xlsx file
            wb.SaveToFile("NewSpreadsheet.xlsx", FileFormat.Version2016);
        }
    }
}

C#/VB.NET: Create, Read, or Update Excel Documents

Read Data of a Worksheet in C#, VB.NET

The Worksheet.Range.Value property returns number value or text value of a cell as a string. To get data of a whole worksheet or a cell range, loop through the cells within it. The following are the steps to get data of a worksheet using Spire.XLS for .NET.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Get the cell range containing data though Worksheet.AllocatedRange property.
  • Iterate through the rows and columns to get cells within the range, and return the value of each cell through CellRange.Value property.
  • C#
  • VB.NET
using Spire.Xls;

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

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

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

            //Get the cell range containing data
            CellRange locatedRange = sheet.AllocatedRange;

            //Iterate through the rows
            for (int i = 0;i < locatedRange.Rows.Length;i++)
            {
                //Iterate through the columns
                for (int j = 0; j < locatedRange.Rows[i].ColumnCount; j++)
                {
                    //Get data of a specific cell
                    Console.Write(locatedRange[i + 1, j + 1].Value + "  ");

                }
                Console.WriteLine();            
            }
        }
    }
}

C#/VB.NET: Create, Read, or Update Excel Documents

Update an Excel Document in C#, VB.NET

To change the value of a certain cell, just re-assign a value to it through Worksheet.Range.Value property. The following are the detailed steps.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Change the value of a particular cell though Worksheet.Range.Value property.
  • Save the workbook to an Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

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

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

            //Change the value of a specific cell
            sheet.Range["A1"].Value = "Updated Value";

            //Save to file
            wb.SaveToFile("Updated.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Create, Read, or Update Excel Documents

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 Document Operation
Wednesday, 27 July 2011 03:30

Load/Save Excel VBA in C#, VB.NET

By running VBA within the Office applications, developers/programmers can build customized solutions and programs to enhance the capabilities of those applications. The VBA function of Excel is very powerful. Below I will show you how to use VBA by Spire.XLS.

VBA is the acronym for VB.NET for Applications. It is an implementation of Microsoft's event-driven programming language VB.NET 6 and its associated integrated development environment (IDE), which are built into most Microsoft Office applications. VBA is closely related to VB.NET and uses the VB.NET Runtime Library, but can normally only run code within a host application rather than as a standalone program. It can be used to control one application from another via OLE Automation.

Spire.XLS for .NET is a professional Excel .NET component that can be linked into any type of .NET 2.0, 3.5 or 4.0 projects, either ASP.NET web sites or Windows Forms application. Spire.XLS for .NET offers a combination of APIs and GUI controls for speeding up Excel programming in .NET platform-create new Excel documents from scratch, edit existing Excel documents and convert Excel files. At the same time, Spire.XLS supports VBA and it can load/Save Excel VBA.

Here comes to the steps:

  • Write a template with VBA program with which you can execute your work in Excel.
  • Create another workbook to load the VBA template.

In this demo, it generates a new worksheet named "test" with the VBA template we provide.

Please check the codes as below:

[C#]
using Spire.Xls;

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

            //Initailize worksheet
            workbook.LoadFromFile("VBASample.xls");
            Worksheet sheet = workbook.Worksheets[0];

            //VBA function
            sheet.Range["A1"].Text = "test";

            //Save the file
            workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);

            //Launch the file
            System.Diagnostics.Process.Start("Sample.xls");
        }
    }
}
[VB.NET]
Imports Spire.Xls

Module Module1

    Sub Main()
        'Create a workbook
        Dim workbook As New Workbook()

        'Initailize worksheet
        workbook.LoadFromFile("VBASample.xls")
        Dim sheet As Worksheet = workbook.Worksheets(0)

        'VBA function
        sheet.Range("A1").Text = "test"

        'Save doc file.
        workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003)

        'Launching the MS Word file.
        System.Diagnostics.Process.Start("Sample.xls")
    End Sub
End Module
Published in Document Operation
Friday, 01 July 2011 02:51

Marker Designer

Introduction

A Marker Designer represents a single data point or value that gives a mean to Spire.XLS to place relevant data into different cells of the worksheet in a workbook. We make use of Designer spreadsheets in which we write marker designers into different cells. Normally a marker designer consists of DataSource and a Field Name and starts with "&=". The DataSource can be a DataSet, DataTable, DataView or an Object variable etc. You can also make use of dynamic formulas that allows you to insert MS Excel's formulas into cells even when the formula must reference rows that will be inserted during the export process. Moreover, you may calculate totals and sub totals of any data field too.

Marker designer is a way to let Spire.XLS know that what information you wish to place in an Excel designer spreadsheet. Marker designers allow you to create templates that contain only relevant information and are formatted to meet your needs.

Designer Spreadsheet and Marker Designers

Designer spreadsheets are standard Excel files that contain the visual formatting, formulas and marker designers. They can contain marker designers that reference one or more data sources such as information from a project and information for related contacts. Marker designers are written into cells where you want information to be filled in.

All marker designers start with "&=", without the quotes. An example of a data marker is &=Party.FullName. If the data marker results in more than one item, i.e. row then following rows will be moved down automatically to make room for all of the new information. Thus sub-totals and totals can be placed on the following row after the data marker to make calculations based on inserted data. In order to make calculations on the rows that are inserted, you must use Dynamic Formulas.

Marker designers consist of the Data Source and Field Name parts for most information. Special information may also be passed with variables and variable arrays. Variables always fill only one cell whereas variable arrays may fill several ones. You may only use one data marker per cell. Unused marker designers will be removed.

Marker designer may also contain parameters. Parameters allow you to modify how the information will be laid out. They are appended to the end of marker designer in parenthesis as a comma separated list.

Marker designer Options

&=DataSource.FieldName 
&=[Data Source].[Field Name] 
&=VariableName

Formulas

Formulas allow you to insert Excel's formulas into cells even when the formula must reference rows that will be inserted during the export process. And they can repeat for each inserted row or use only the cell where the data marker is placed for it.

If value of a cell referred to other cells, such as (copy:rc6), it means the value of the cell will be referred by cells of column 6. Multiple refer can be used like this: (copy:rc5,copy:rc7).

Note: Separate them with comma

Cell "G6" contains the formula = D6*E6, cell "G7" contains = D7*E7 and cell "G8" contains = D8*E8, etc.

The following illustrates a repeating dynamic formula and the resulting Excel worksheet.

Excel Marker Designer

Result:

Excel Marker Designer

Sum and Subtotal

Below is showing you how to use these 2 formulas:

Excel Marker Designer

Result:

Excel Marker Designer

Code:

          Workbook workbook = new Workbook();

            workbook.LoadFromFile(@"..\..\..\..\..\..\Data\MarkerDesignerSample1.xls");
			DataTable dt = (DataTable)dataGrid1.DataSource;

			Worksheet sheet = workbook.Worksheets[0];
            //fill parameter
            workbook.MarkerDesigner.AddParameter("Variable1", 1234.5678);
            //fill DataTable
			workbook.MarkerDesigner.AddDataTable("Country",dt);
			workbook.MarkerDesigner.Apply();

            //AutoFit
			sheet.AllocatedRange.AutoFitRows();
			sheet.AllocatedRange.AutoFitColumns();

			workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);

Marker Designer Full Demo

Published in Smart Marker
Monday, 24 January 2011 09:49

Save Excel Document in C#, VB.NET

Automation of an Excel file allows us to doing various operations in C#/VB.NET. Any loss in these operations may result in unexpected negative consequences for developers and the clients of the developers. That means we must find a solution that enables us to Save Excel with no loss in quality of our operations. This section will demonstrate how to fast save Excel file with perfect performance as directly operations in Excel files.

Spire.Xls for .NET is a professional component that enables developers directly manages Excel operation regardless whether Microsoft Excel is installed on or not. With Spire.Xls for .NET, we can save Excel to what we want it to be. Any kind of trial and evaluation on Spire.Xls for .NET is always welcomed; so now please feel free to download Spire.Xls for .NET and then follow our guide to save perfect Excel or try other function of Spire.Xls for .NET.

Spire.Xls for .NET allows us to create a new Excel file, write data in to it, edit the input data and then save Excel file.

[C#]
using Spire.Xls;
namespace Excel_save
{
   class Program
    {
        static void Main(string[] args)
        {
           //Create a new workbook
            Workbook workbook = new Workbook();
           //Initialize worksheet        
            Worksheet sheet = workbook.Worksheets[0];           
           //Append text
            sheet.Range["A1"].Text = "Demo: Save Excel in .NET";
           //Save it as Excel file
            workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);
           //Launch the file
           System.Diagnostics.Process.Start(workbook.FileName);
        }
    }
}
[VB.NET]
Imports Spire.Xls
Namespace Excel_save
	Class Program
		Private Shared Sub Main(args As String())
			'Create a new workbook
			Dim workbook As New Workbook()
			'Initialize worksheet        
			Dim sheet As Worksheet = workbook.Worksheets(0)
			'Append text
			sheet.Range("A1").Text = "Demo: Save Excel in .NET"
			'Save it as Excel file
			workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003)
			'Launch the file
			System.Diagnostics.Process.Start(workbook.FileName)
		End Sub
	End Class
End Namespace
Published in Document Operation
Page 2 of 2