Data (27)
Spire.XLS for .NET is a professional Excel component which enables developers/programmers to fast generate, read, write and modify Excel document for .NET. Spire.XLS for .NET doesn't need Microsoft Office Excel Automation. It allows user to operate Excel document directly such as save to stream, save as web response, copy, lock/unlock worksheet, set up workbook properties, etc. As a professional .NET Excel component, it also includes many useful features, for example, functionalities of importing data from Excel to dataTable and exporting dataTable to Excel from Database.
In this article introduces a method of updating excel data by dataTable via using sheet.ExportDataTable() method and sheet.InsertDataTable() method to import data from excel to dataTable and export dataTable to excel from Database.
The main steps of method are:
Step 1: Load the excel document and use sheet.ExportDataTable() method extract data to dataTable and show by dataGridView control.
private void Form1_Load(object sender, EventArgs e) { //load excel document to workbook workbook.LoadFromFile(@"DatatableSample.xls"); Worksheet sheet = workbook.Worksheets[0]; sheet.Name = "Original table"; //extract data to dataTable from sheet DataTable dataTable = sheet.ExportDataTable(); //show the data to dataGridView this.dataGridView.DataSource = dataTable; }
The effect screenshot:
Step 2: Create a new sheet to save the updata data and use sheet.InsertDataTable() method to insert dataTable to the sheet.
//create a new sheet to save Updata data. Worksheet sheet = workbook.CreateEmptySheet("Updata Table"); //extract data from dataGridView DataTable dataTable = this.dataGridView.DataSource as DataTable; // insert dataTable to sheet sheet.InsertDataTable(dataTable, true, 1, 1);
Step 3: Save the result excel document.
workbook.SaveToFile("result.xlsx", ExcelVersion.Version2007);
The effect screenshot:
Download and install Spire.XLS for .NET and use below code to experience this method to update excel data by dataTable.
The full code:
using System; using System.Data; using System.Windows.Forms; using Spire.Xls; namespace UpdataExcelDataByDataTable { public partial class UpdataExcelData : Form { private Workbook workbook = new Workbook(); private void Form1_Load(object sender, EventArgs e) { workbook.LoadFromFile(@"DatatableSample.xls"); Worksheet sheet = workbook.Worksheets[0]; sheet.Name = "Original table"; DataTable dataTable = sheet.ExportDataTable(); this.dataGridView.DataSource = dataTable; } private void Updata_Click(object sender, EventArgs e) { Worksheet sheet = workbook.CreateEmptySheet("Updata Table"); DataTable dataTable = this.dataGridView.DataSource as DataTable; sheet.InsertDataTable(dataTable, true, 1, 1); workbook.SaveToFile("result.xlsx", ExcelVersion.Version2007); System.Diagnostics.Process.Start("result.xlsx"); } } }
Imports System.Data Imports System.Windows.Forms Imports Spire.Xls Public Class Form1 Private workbook As New Workbook() Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 'load excel document to workbook workbook.LoadFromFile("DatatableSample.xls") Dim sheet As Worksheet = workbook.Worksheets(0) sheet.Name = "Original table" 'extract data to dataTable from sheet Dim dataTable As DataTable = sheet.ExportDataTable() 'show the data to dataGridView Me.DataGridView.DataSource = dataTable End Sub
If you couldn't successfully use the Spire.Xls, please refer Spire.XLS Quick Start which can guide you quickly use the Spire.Xls.
Superscript and subscript are formatting styles that allow you to display characters or numerals above or below the regular text baseline respectively. By utilizing these formatting styles, you can emphasize certain elements, denote exponents, powers, chemical formulas, or mathematical equations, and present data in a more visually appealing and informative manner. In this article, we will demonstrate how to apply superscript and subscript styles in Excel 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
Apply Superscript and Subscript in Excel in C# and VB.NET
To apply the superscript or subscript style to specific characters in a cell, you need to create a custom font, enable the superscript or subscript property of the font, and then assign the custom font to the specific characters within the cell. The detailed steps are as follows:
- Create a Workbook object.
- Get a specific worksheet using Workbook.Worksheets[int index] property.
- Get a specific cell using Worksheet.Range[string name] property and add rich text to the cell using CellRange.RichText.Text property.
- Create a custom font using Workbook.CreateFont() method.
- Enable the subscript property of the font by setting ExcelFont.IsSubscript property to true.
- Assign the custom font to specific characters of the rich text in the cell using CellRange.RichText.SetFont() method.
- Get a specific cell using Worksheet.Range[string name] property and add rich text to the cell using CellRange.RichText.Text property.
- Create a custom font using Workbook.CreateFont() method.
- Enable the superscript property of the font by setting ExcelFont.IsSuperscript property to true.
- Assign the custom font to specific characters of the rich text in the cell using CellRange.RichText.SetFont() method.
- Save the result file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls; using System.Drawing; namespace ApplySuperscriptAndSubscript { internal class Program { static void Main(string[] args) { //Create a Workbook object Workbook workbook = new Workbook(); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Add text to specific cells sheet.Range["B2"].Text = "This is an example of subscript:"; sheet.Range["D2"].Text = "This is an example of superscript:"; //Add rich text to a specific cell CellRange range = sheet.Range["B3"]; range.RichText.Text = "an = Sn - Sn-1"; //Create a custom font ExcelFont font = workbook.CreateFont(); //Enable the subscript property of the font font.IsSubscript = true; //Set font color font.Color = Color.Green; //Assign the font to specific characters of the rich text in the cell range.RichText.SetFont(6, 6, font); range.RichText.SetFont(11, 13, font); //Add rich text to a specific cell range = sheet.Range["D3"]; range.RichText.Text = "a2 + b2 = c2"; //Create a custom font font = workbook.CreateFont(); //Enable the superscript property of the font font.IsSuperscript = true; //Assign the font to specific characters of the rich text in the cell range.RichText.SetFont(1, 1, font); range.RichText.SetFont(6, 6, font); range.RichText.SetFont(11, 11, font); //Auto-fit column widths sheet.AllocatedRange.AutoFitColumns(); //Save the result file workbook.SaveToFile("ApplySubscriptAndSuperscript.xlsx", ExcelVersion.Version2013); workbook.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
You can hide the Excel row or column by using the c# code, but a row or column also becomes hidden when you want to show the full Excel worksheet. You can unhide the Excel row and column by using the c# code. This article aims at introducing the method sheet.ShowRow and sheet.ShowColumn in the Excel .NET component Spire.Xls to show the hidden row and column.
First, let’s preview the hidden row and column.
Here comes to the steps of the process.
Step 1: Create an instance of Spire.XLS.Workbook.
Workbook workbook = new Workbook();
Step 2: Load the existing Excel file that hidden the row and column in the specified path.
workbook.LoadFromFile("hide.xlsx");
Step 3: Get the first worksheet of the Excel file.
Worksheet sheet = workbook.Worksheets[0];
Step 4: Unhide the hidden row and column.
sheet.ShowRow(7); sheet.ShowColumn(3);
Step 5: Generate the new Excel file.
workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);
Now let's preview the effect screenshot.
Here is the full code.
using Spire.Xls; namespace UnhideExcelRow { class Program { static void Main(string[] args) { Workbook workbook = new Workbook(); workbook.LoadFromFile("hide.xlsx"); Worksheet sheet = workbook.Worksheets[0]; // unhide the hidden row and column of the worksheet. sheet.ShowRow(7); sheet.ShowColumn(3); workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010); } } }
Text alignment and orientation are essential formatting features in Excel that allow you to position and orient text within cells according to your specific needs. By adjusting text alignment and orientation, you can enhance the readability and aesthetics of your spreadsheet. In this article, we will explain how to set text alignment and orientation in Excel 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
Set Text Alignment and Orientation in Excel in C# and VB.NET
You can set the horizontal or vertical alignment of text in individual cells or a range of cells using the CellRange.Style.HorizontalAlignment or CellRange.Style.VerticalAlignment properties. In addition, you are also able to change the orientation of text by assigning a rotation value to the corresponding cell or cells using the CellRange.Style.Rotation property. The detailed steps are as follows:
- Create a Workbook object.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[int index] property.
- Access specific cells in the worksheet using Worksheet.Range[string name] property and then set the horizontal alignment of text in them using CellRange.Style.HorizontalAlignment property.
- Access specific cells in the worksheet using Worksheet.Range[string name] property and then set the vertical alignment of text in them using CellRange.Style.VerticalAlignment property.
- Access specific cells in the worksheet using Worksheet.Range[string name] property and then change their text orientation using CellRange.Style.Rotation property.
- Save the result file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls; namespace TextAlignmentAndRotation { internal 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 sheet = workbook.Worksheets[0]; //Set the horizontal alignment for text in a specific cell to Left sheet.Range["B1"].Style.HorizontalAlignment = HorizontalAlignType.Left; //Set the horizontal alignment for text in a specific cell to Center sheet.Range["B2"].Style.HorizontalAlignment = HorizontalAlignType.Center; //Set the horizontal alignment for text in a specific cell to Right sheet.Range["B3"].Style.HorizontalAlignment = HorizontalAlignType.Right; //Set the horizontal alignment for text in a specific cell to General sheet.Range["B4"].Style.HorizontalAlignment = HorizontalAlignType.General; //Set the vertical alignment for text in a specific cell to Top sheet.Range["B5"].Style.VerticalAlignment = VerticalAlignType.Top; //Set the vertical alignment for text in a specific cell to Center sheet.Range["B6"].Style.VerticalAlignment = VerticalAlignType.Center; //Set the vertical alignment for text in a specific cell to Bottom sheet.Range["B7"].Style.VerticalAlignment = VerticalAlignType.Bottom; //Change the text orientation in specific cells by assigning a rotation value sheet.Range["B8"].Style.Rotation = 45; sheet.Range["B9"].Style.Rotation = 90; //Set the row height for specific cells sheet.Range["B8:C9"].RowHeight = 70; //Save the result file workbook.SaveToFile("TextAlignmentAndOrientation.xlsx", ExcelVersion.Version2016); workbook.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Group the Excel cells is to tie a range of cells together so that they can be collapsed or expanded. But usually, we also need to ungroup the Excel cells. Consequently, the articles aims at introducing how to ungroup Excel cells in C#, through a professional Excel .NET Component Spire.Xls.
Just as its name implies, ungroup Excel cells is to ungroup a range of cells that were previously grouped. Before ungroup Excel cells, we should complete the preparatory work:
- Download the 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.
- Add Spire.XLS as namespace.
Then here comes to the explanation of the code:
Step 1: Create an instance of Spire.XLS.Workbook.
Workbook workbook = new Workbook();
Step 2: Load the file base on a specified file path.
workbook.LoadFromFile(@"group.xlsx");
Step 3: Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
Step 4: Ungroup the first 5 row cells.
sheet.UngroupByRows(1, 5);
Step 5: Save as the generated file.
workbook.SaveToFile(@"result.xlsx", ExcelVersion.Version2010);
Full code:
using Spire.Xls; namespace UngroupCell { class Program { static void Main(string[] args) { Workbook workbook = new Workbook(); workbook.LoadFromFile(@"group.xlsx"); Worksheet sheet = workbook.Worksheets[0]; sheet.UngroupByRows(1, 5); workbook.SaveToFile(@"..\..\result.xlsx", ExcelVersion.Version2010); } } }
Please preview the original group effect screenshot:
And the generated ungroup effect screenshot:
The Find function in Excel is one of the most commonly used functions for quickly locating specified data, and users can also highlight the data to make it more obvious. In this article, you will learn how to programmatically find and highlight cells with a specific value 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
Find and Highlight Data in Excel
The detailed steps are as follows.
- Create a Workbook instance.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
- Find all cells with matching text using Worksheet.FindAllString(string stringValue, bool formula, bool formulaValue) method.
- Set color to highlight the cells using CellRange.Style.Color property.
- Save the result file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls; using System.Drawing; namespace FindHighlight { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load a sample Excel file workbook.LoadFromFile("Test.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Find all cells with the text "Regulator System" foreach (CellRange range in sheet.FindAllString("Regulator System", true, true)) { //Set color to highlight the cells range.Style.Color = Color.Yellow; } //Save the result file workbook.SaveToFile("FindHighlight.xlsx", ExcelVersion.Version2016); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Excel's Find and Replace feature is an indispensable tool for users when editing large Excel spreadsheets. It allows users to search for specific values within a worksheet or cell range and update them with new values quickly and accurately. With this feature, users don't need to perform manual searches, which significantly improves their working efficiency. In this article, we will introduce how to programmatically find and replace data in Excel in C# and VB.NET using Spire.XLS for .NET library.
- Find and Replace Data in a Worksheet in Excel
- Find and Replace Data in a Specific Cell Range in Excel
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
Find and Replace Data in a Worksheet in Excel in C# and VB.NET
Spire.XLS for .NET offers the Worksheet.FindAllString(string stringValue, bool formula, bool formulaValue) method which enables you to find the cells containing specific data values in an Excel worksheet. Once the cells are found, you can use the CellRange.Text property to update their values with new values. The detailed steps are as follows:
- Initialize an instance of the Workbook class.
- Load an Excel file using the Workbook.LoadFromFile(string fileName) method.
- Get a specific worksheet of the file using the Workbook.Worksheets[int index] property.
- Find the cells containing a specific value in the worksheet using the Worksheet.FindAllString(string stringValue, bool formula, bool formulaValue) method.
- Iterate through the found cells.
- Update the value of each cell with another value using the CellRange.Text property.
- Set a background for the cell so you can easily find the updated cells using the CellRange.Style.Color property.
- Save the result file to a specific location using the Workbook.SaveToFile(string fileName, ExcelVersion version) method.
- C#
- VB.NET
using Spire.Xls; using System.Drawing; namespace ReplaceDataInWorksheet { internal class Program { static void Main(string[] args) { //Initialize an instance of the Workbook class Workbook workbook = new Workbook(); //Load an Excel file workbook.LoadFromFile(@"Sample.xlsx"); //Get the first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Find the cells with the specific string value “Total” in the worksheet CellRange[] cells = worksheet.FindAllString("Total", true, true); //Iterate through the found cells foreach (CellRange cell in cells) { //Replace the value of the cell with another value cell.Text = "Sum"; //Set a background color for the cell cell.Style.Color = Color.Yellow; } //Save the result file to a specific location workbook.SaveToFile("ReplaceDataInWorksheet.xlsx", ExcelVersion.Version2016); workbook.Dispose(); } } }
Find and Replace Data in a Specific Cell Range in Excel in C# and VB.NET
You can find the cells containing a specific value in a cell range using the CellRange.FindAllString(string stringValue, bool formula, bool formulaValue) method. Then you can update the value of each found cell with another value using the CellRange.Text property. The detailed steps are as follows:
- Initialize an instance of the Workbook class.
- Load an Excel file using the Workbook.LoadFromFile(string fileName) method.
- Get a specific worksheet of the file using the Workbook.Worksheets[int index] property.
- Get a specific cell range of the worksheet using the Worksheet.Range[string rangeName] property.
- Find the cells with a specific value in the cell range using the CellRange.FindAllString(string stringValue, bool formula, bool formulaValue) method.
- Iterate through the found cells.
- Update the value of each found cell to another value using the CellRange.Text property.
- Set a background for the cell so you can easily find the updated cells using the CellRange.Style.Color property.
- Save the result file to a specific location using the Workbook.SaveToFile(string fileName, ExcelVersion version) method.
- C#
- VB.NET
using Spire.Xls; using System.Drawing; namespace ReplaceDataInCellRange { internal class Program { static void Main(string[] args) { //Initialize an instance of the Workbook class Workbook workbook = new Workbook(); //Load an Excel file workbook.LoadFromFile(@"Sample.xlsx"); //Get the first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Get a specific cell range CellRange range = worksheet.Range["A1:C9"]; //Find the cells with the specific value "Total" in the cell range CellRange[] cells = range.FindAllString("Total", true, true); //Iterate through the found cells foreach (CellRange cell in cells) { //Replace the value of the cell with another value cell.Text = "Sum"; //Set a background color for the cell cell.Style.Color = Color.Yellow; } //Save the result file to a specific location workbook.SaveToFile("ReplaceDataInCellRange.xlsx", ExcelVersion.Version2016); workbook.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Sorting in Excel is one of the most commonly used features in data analysis. It allows users to sort text, numbers, dates and times in ascending, descending or alphabetical order. This article will demonstrate how to programmatically sort data in a cell range 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
Sort Data in Excel
The detailed steps are as follows.
- Create a Workbook instance.
- Load a sample Excel document using Workbook.LoadFromFile() method.
- Get the first worksheet using Workbook.Worksheets[index] property.
- Get a sort fields collection using Workbook.DataSorter.SortColumns property, and then specify the column that need to be sorted and the sort mode in the collection using SortColumns.Add(Int key, SortComparsionType, OrderBy) method.
- Sort the data in the specified cell range using Workbook.DataSorter.Sort(CellRange range) method.
- Save the result document using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls; namespace SortData { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load a sample Excel document workbook.LoadFromFile("sample.xlsx"); //Get the first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Specify the column that need to be sorted and the sort mode (ascending or descending) workbook.DataSorter.SortColumns.Add(0, SortComparsionType.Values, OrderBy.Ascending); //Sort data in the specified cell range workbook.DataSorter.Sort(worksheet.Range["A1:D10"]); //Save the result document workbook.SaveToFile("Sort.xlsx", ExcelVersion.Version2016); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
In Excel, the content of a cell may look incomplete when it exceeds the length of the cell. Under the circumstance, you can apply wrap text in the cell to ensure that all content can be viewed at once. This article will demonstrate how to programmatically wrap or unwrap text in Excel cells 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
Wrap or Unwrap Text in Excel Cells
The detailed steps are as follows.
- Create a Workbook object.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specified worksheet using Workbook.Worksheets[] property.
- Get a specified cell using Worksheet.Range[] property.
- Get the style of the specified cell using CellRange.Style property.
- Wrap text in the specified cell by setting the CellStyle.WrapText property to true. Or set the property to false to unwrap text in the specified cell.
- Save the result file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls; namespace WrapText { class Program { static void Main(string[] args) { //Create a Workbook object Workbook workbook = new Workbook(); //Load a sample Excel file workbook.LoadFromFile(@"D:\Files\sample.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Wrap text in cell B3 sheet.Range["B3"].Style.WrapText = true; //Unwrap text in cell B7 sheet.Range["B7"].Style.WrapText = false; //Save the result file workbook.SaveToFile("WarpText.xlsx", ExcelVersion.Version2010); } } }
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.
Set an Array of Values into a Range in Excel Worksheet
2011-08-17 05:56:20 Written by support iceblueQuestion:
I'm trying to set an array of values into a range in Excel Worksheet. This is possible via Microsoft Excel object and allows setting values very quickly. How to use Spire.XLS to manage it?
Answer:
It is possible to output an array of data to a range of worksheet via Spire.XLS. Using arrays sheet.InsertArray() method and the following sample source codes for your reference would be helpful.
using Spire.Xls; namespace SetArrayofValues { class Program { private void SetArrayValueExample() { Workbook workbook = new Workbook(); workbook.CreateEmptySheets(1); Worksheet sheet = workbook.Worksheets[0]; int maxRow = 10000; //int maxRow = 5; int maxCol = 200; //int maxCol = 5; object[,] myarray = new object[maxRow + 1, maxCol + 1]; bool[,] isred = new bool[maxRow + 1, maxCol + 1]; for (int i = 0; i <= maxRow; i++) for (int j = 0; j <= maxCol; j++) { myarray[i, j] = i + j; if ((int)myarray[i, j] > 8) isred[i, j] = true; } sheet.InsertArray(myarray, 1, 1); workbook.SaveToFile("test.xls",ExcelVersion.Version97to2003); } } }
If this doesn't answer your question, please do not hesitate to add your question in our forum. Our technical support will answer soon (we promise response within 1 business day)!