
.NET (1288)
Children categories
Spire.DataExport, as a 100% pure .NET component suit for data exporting from SQL Command, Listview and DataTable into MS Excel,MS Word, HTML, XML, PDF, MS Access, DBF, SQL Script, SYLK, DIF, CSV ,MS Clipboard format, quickly and easily! Here we will introduce how to export data from Listview to Excel with C#/VB.NET.
As an electronic spreadsheet program, MS Excel owns a lot of advantages such as it can be used for storing, organizing and manipulating data. Over several decades, Microsoft has updated, expanded and tweaked Excel to keep up with both modern technology and the needs of spreadsheet users. MS Excel has been the most popular data organizing program. So we may usually need export data from database into Excel, such as from ListView.
Spire.DataExport presents an easy way to export data from Listview to Excel. And it offers both C# and VB.Net language to realize it
Download Spire.DataExport (or Spire.Office) with .NET framework together and use the code below to export data from Listview to Excel with C# and VB.NET.
this.cellExport1.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView; this.cellExport1.AutoFitColWidth = true; this.cellExport1.DataFormats.CultureName = "en-us"; this.cellExport1.DataFormats.Currency = "?#,###,##0.00"; this.cellExport1.DataFormats.DateTime = "yyyy-M-d H:mm"; this.cellExport1.DataFormats.Float = "#,###,##0.00"; this.cellExport1.DataFormats.Integer = "#,###,##0"; this.cellExport1.DataFormats.Time = "H:mm"; this.cellExport1.FileName = "sample.xls"; this.cellExport1.SheetOptions.AggregateFormat.Font.Name = "Arial"; this.cellExport1.SheetOptions.CustomDataFormat.Font.Name = "Arial"; this.cellExport1.SheetOptions.DefaultFont.Name = "Arial"; this.cellExport1.SheetOptions.FooterFormat.Font.Name = "Arial"; this.cellExport1.SheetOptions.HeaderFormat.Font.Name = "Arial"; this.cellExport1.SheetOptions.HyperlinkFormat.Font.Color = Spire.DataExport.XLS.CellColor.Blue; this.cellExport1.SheetOptions.HyperlinkFormat.Font.Name = "Arial"; this.cellExport1.SheetOptions.HyperlinkFormat.Font.Underline = Spire.DataExport.XLS.XlsFontUnderline.Single; this.cellExport1.SheetOptions.NoteFormat.Alignment.Horizontal = Spire.DataExport.XLS.HorizontalAlignment.Left; this.cellExport1.SheetOptions.NoteFormat.Alignment.Vertical = Spire.DataExport.XLS.VerticalAlignment.Top; this.cellExport1.SheetOptions.NoteFormat.Font.Bold = true; this.cellExport1.SheetOptions.NoteFormat.Font.Name = "Tahoma"; this.cellExport1.SheetOptions.NoteFormat.Font.Size = 8F; this.cellExport1.SheetOptions.TitlesFormat.Font.Bold = true; this.cellExport1.SheetOptions.TitlesFormat.Font.Name = "Arial"; this.cellExport1.DataSource = ExportSource.ListView; this.cellExport1.ListView = this.ListView1; cellExport1.SaveToFile(); ListView to Excel with VB.NET Code
Me.cellExport1.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView Me.cellExport1.AutoFitColWidth = True Me.cellExport1.DataFormats.CultureName = "en-us" Me.cellExport1.DataFormats.Currency = "?#,###,##0.00" Me.cellExport1.DataFormats.DateTime = "yyyy-M-d H:mm" Me.cellExport1.DataFormats.Float = "#,###,##0.00" Me.cellExport1.DataFormats.Integer = "#,###,##0" Me.cellExport1.DataFormats.Time = "H:mm" Me.cellExport1.FileName = "sample.xls" Me.cellExport1.SheetOptions.AggregateFormat.Font.Name = "Arial" Me.cellExport1.SheetOptions.CustomDataFormat.Font.Name = "Arial" Me.cellExport1.SheetOptions.DefaultFont.Name = "Arial" Me.cellExport1.SheetOptions.FooterFormat.Font.Name = "Arial" Me.cellExport1.SheetOptions.HeaderFormat.Font.Name = "Arial" Me.cellExport1.SheetOptions.HyperlinkFormat.Font.Color = Spire.DataExport.XLS.CellColor.Blue Me.cellExport1.SheetOptions.HyperlinkFormat.Font.Name = "Arial" Me.cellExport1.SheetOptions.HyperlinkFormat.Font.Underline = Spire.DataExport.XLS.XlsFontUnderline.Single Me.cellExport1.SheetOptions.NoteFormat.Alignment.Horizontal = Spire.DataExport.XLS.HorizontalAlignment.Left Me.cellExport1.SheetOptions.NoteFormat.Alignment.Vertical = Spire.DataExport.XLS.VerticalAlignment.Top Me.cellExport1.SheetOptions.NoteFormat.Font.Bold = True Me.cellExport1.SheetOptions.NoteFormat.Font.Name = "Tahoma" Me.cellExport1.SheetOptions.NoteFormat.Font.Size = 8.0! Me.cellExport1.SheetOptions.TitlesFormat.Font.Bold = True Me.cellExport1.SheetOptions.TitlesFormat.Font.Name = "Arial" Me.cellExport1.DataSource = Common.ExportSource.ListView Me.cellExport1.ListView = Me.ListView1 cellExport1.SaveToFile() End Sub
Watermarks are text or images displayed fadedly or in gray color in the background of a Word document. They can be used to declare confidentiality, copyright, or other attributes of the document, or just as decorations to make the document more attractive. This article shows an easy way to insert watermarks in Word documents with the help of Spire.Doc for .NET, including text watermarks and image watermarks.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc 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.Doc
Insert a Text Watermark in a Word Document
The detailed steps are as follows:
- Create an object of Document class.
- Load a Word document from disk using Document.LoadFromFile() method.
- Insert a text watermark in the document using custom method InsertTextWatermark().
- Save the document using Doucment.SaveToFile() method.
- C#
- VB.NET
using System; using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; namespace InsertImageWatermark { internal class Program { static void Main(string[] args) { //Create an object of Document class Document document = new Document(); //Load a Word document from disk document.LoadFromFile(@"D:\Samples\Sample.docx"); //Insert a text watermark InsertTextWatermark(document.Sections[0]); //Save the document document.SaveToFile("InsertTextWatermark.docx", FileFormat.Docx); } private static void InsertTextWatermark(Section section) { TextWatermark txtWatermark = new TextWatermark(); txtWatermark.Text = "DO NOT COPY"; txtWatermark.FontSize = 50; txtWatermark.Color = Color.Blue; txtWatermark.Layout = WatermarkLayout.Diagonal; section.Document.Watermark = txtWatermark; } } }
Insert an Image Watermark in a Word Document
The detailed steps are as follows:
- Create an object of Document class.
- Load a Word document from disk using Document.LoadFromFile() method.
- Insert an image watermark in the document using custom method InsertImageWatermark().
- Save the document using Document.SaveToFile() method.
- C#
- VB.NET
using System; using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; namespace InsertWatermark { internal class Program { static void Main(string[] args) { //Create an object of Document class Document document = new Document(); //Load a Word document from disk document.LoadFromFile(@"D:\Samples\Sample.docx"); //Insert an image watermark InsertImageWatermark(document); //Save the document document.SaveToFile("InsertImageWatermark.docx", FileFormat.Docx); } private static void InsertImageWatermark(Document document) { PictureWatermark picture = new PictureWatermark(); picture.Picture = Image.FromFile(@"D:\Samples\Watermark.png"); picture.Scaling = 200; picture.IsWashout = false; document.Watermark = picture; } } }
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.
How to Split PDF Files in C# .NET (Complete Guide with Code Examples)
2022-06-28 07:52:00 Written by KoohjiSplitting PDF files programmatically is a crucial step for automating document management in many C# and .NET applications. Whether you need to extract specific pages, divide PDFs by defined ranges, or organize large reports, using code to segment PDFs saves time and improves accuracy.
This comprehensive guide shows how to programmatically split or divide PDF files in C# using the Spire.PDF for .NET library, with practical methods and clear code examples to help developers easily integrate PDF splitting into their applications.
Table of Contents
- Why Split a PDF Programmatically in C#?
- What You Need to Get Started
- Installing Spire.PDF for .NET Library
- How to Split PDF Files in C# (Methods and Code Examples)
- Split PDF in VB.NET
- Conclusion
- Frequently Asked Questions (FAQs)
Why Split a PDF Programmatically in C#?
Splitting PDFs through code offers significant advantages over manual processing. It enables:
- Automated report generation
- Faster document preparation in enterprise workflows
- Easy content extraction for archiving or redistribution
- Dynamic document handling based on user or system input
It also reduces the risk of human error and ensures consistency across repetitive tasks.
What You Need to Get Started
Before diving into the code, make sure you have:
- .NET Framework or .NET Core installed
- Visual Studio or another C# IDE
- Spire.PDF for .NET library installed
- Basic familiarity with C# programming
Installing Spire.PDF for .NET Library
Spire.PDF for .NET is a professional .NET library that enables developers to create, read, edit, and manipulate PDF files without Adobe Acrobat. It supports advanced PDF operations like splitting, merging, extracting text, adding annotations, and more.
You can install Spire.PDF for .NET NuGet Package via NuGet Package Manager:
Install-Package Spire.PDF
Or through the NuGet UI in Visual Studio:
- Right-click your project > Manage NuGet Packages
- Search for Spire.PDF
- Click Install
How to Split PDF Files in C# (Methods and Code Examples)
Breaking PDF by Every Page
When you want to break a PDF into multiple single-page files, the Split method is the easiest way. By specifying the output file name pattern, you can automatically save each page of the PDF as a separate file. This method simplifies batch processing or distributing pages individually.
using Spire.Pdf;
namespace SplitPDF
{
internal class Program
{
static void Main(string[] args)
{
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");
// Split each page into separate PDF files.
// The first parameter is the output file pattern.
// {0} will be replaced by the page number starting from 1.
pdf.Split("Output/Page_{0}.pdf", 1);
pdf.Close();
}
}
}
Dividing PDF by Page Ranges
To divide a PDF into multiple sections based on specific page ranges, the InsertPageRange method is ideal. This example shows how to define page ranges using zero-based start and end page indices, and then extract those ranges into separate PDF files efficiently.
using Spire.Pdf;
namespace SplitPDF
{
internal class Program
{
static void Main(string[] args)
{
// Load the PDF
PdfDocument document = new PdfDocument();
document.LoadFromFile("Sample.pdf");
// Define two ranges — pages 1–6 and 7–13 (0-based index)
int[][] ranges = new int[][]
{
new int[] { 0, 5 },
new int[] { 6, 12 }
};
// Split the PDF into smaller files by the predefined page ranges
for (int i = 0; i < ranges.Length; i++)
{
int startPage = ranges[i][0];
int endPage = ranges[i][1];
PdfDocument rangePdf = new PdfDocument();
rangePdf.InsertPageRange(document, startPage, endPage);
rangePdf.SaveToFile($"Output/Pages_{startPage + 1}_to_{endPage + 1}.pdf");
rangePdf.Close();
}
document.Close();
}
}
}
Splitting PDF by Text or Keywords
To perform content-based PDF splitting, use the Find method of the PdfTextFinder class to locate pages containing specific keywords. Once identified, you can extract these pages and insert them into new PDF files using the InsertPage method. This approach enables precise page extraction based on document content instead of fixed page numbers.
using Spire.Pdf;
using Spire.Pdf.Texts;
using System.Collections.Generic;
namespace SplitPDF
{
internal class Program
{
static void Main(string[] args)
{
// Load the PDF document
PdfDocument document = new PdfDocument();
document.LoadFromFile("Sample.pdf");
// Create a new PDF to hold extracted pages
PdfDocument resultDoc = new PdfDocument();
string keyword = "Market";
// Loop through all pages to find the keyword
for (int i = 0; i < document.Pages.Count; i++)
{
PdfPageBase page = document.Pages[i];
PdfTextFinder finder = new PdfTextFinder(page);
// Set search options
finder.Options.Parameter = TextFindParameter.WholeWord;
finder.Options.Parameter = TextFindParameter.IgnoreCase;
// Find keyword on the page
List<PdfTextFragment> fragments = finder.Find(keyword);
// If keyword found, append the page to result PDF
if (fragments.Count > 0)
{
resultDoc.InsertPage(document, page);
}
}
// Save the result PDF
resultDoc.SaveToFile("Pages_With_Keyword.pdf");
// Dispose resources
document.Dispose();
resultDoc.Dispose();
}
}
}
Extracting Specific Pages from PDF
Sometimes you only need to extract one or a few individual pages from a PDF instead of splitting the whole document. This example demonstrates how to use the InsertPage method of the PdfDocument class to extract a specific page and save it as a new PDF. This method is useful for quickly pulling out important pages for review or distribution.
using Spire.Pdf;
namespace SplitPDF
{
internal class Program
{
static void Main(string[] args)
{
// Load the PDF file
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");
// Create a new PDF to hold the extracted page
PdfDocument newPdf = new PdfDocument();
// Insert the third page (index 2, zero-based) from the PDF into the new PDF
newPdf.InsertPage(pdf, pdf.Pages[2]);
// Save the new PDF
newPdf.SaveToFile("ExtractPage.pdf");
newPdf.Close();
pdf.Close();
}
}
}
Split PDF in VB.NET
If you're working with VB.NET instead of C#, you don't need to worry about translating the code manually. You can easily convert the C# code examples in this article to VB.NET using our C# to VB.NET code converter. This tool ensures accurate syntax conversion, saving time and helping you stay focused on development.
Conclusion
Splitting PDF files programmatically in C# using Spire.PDF offers a reliable and flexible solution for automating document processing. Whether you're working with invoices, reports, or dynamic content, Spire.PDF supports various splitting methods—by page, page range, or keyword—allowing you to tailor the logic to fit any business or technical requirement.
Frequently Asked Questions (FAQs)
Q1: Is Spire.PDF free to use?
A1: Spire.PDF offers a free version suitable for small-scale or non-commercial use. For full functionality and advanced features, the commercial version is recommended.
Q2: Can I split encrypted PDFs?
A2: Yes, as long as you provide the correct password when loading the PDF files.
Q3: Does Spire.PDF support .NET Core?
A3: Yes, Spire.PDF is compatible with both .NET Framework and .NET Core.
Q4: Can I split and merge PDFs in the same project?
A4: Absolutely. Spire.PDF provides comprehensive support for both splitting and merging operations.
Get a Free License
To fully experience the capabilities of Spire.PDF for .NET without any evaluation limitations, you can request a free 30-day trial license.
What is Excel Interior?
Excel provides essentially no support in worksheet functions for Working with cell colors. However, colors are often used in spreadsheets to indicate some sorts of value or category. Thus comes the need for functions that can work with colors on the worksheet. So it appears in the version in Excel 2007 as a new function. It contains all kinds of colors. Below I will show you how to insert interior in Excel with MS Excel and how to do this with Spire.XLS.
How to insert interior in Excel with MS Excel?
To insert interior in Excel with Microsoft Excel, you can follow the sections below:
- Open the worksheet in Excel
- Highlight the zones that you want to insert interior
- Rightclick and choose Setting Cell Format
- Choose Fill->Fill Effect in the dialog box of Setting Cell Format
- In the box, you can change the Color and the Shade Format to your desired effect
How to Insert Interior with Spire.XLS?
It's convenient to realize C#/.NET Excel Integration via Spire.XLS. In interior method, to realize interior you may set the color gradient by assigning sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.FillPattern property with ExcelPatternType.Gradient. You can set the BackKnownColor and ForeKnownColor of the sheet. What's more, you can set the gradient style, in the demo, we set the gradient style vertical. In order to reflect the effect, we merge the worksheet range from E to K. In this demo, we use Enum method to enumerate many kinds of colors and define a random object to fill the cell with a gradient color randomly.
First, let's preview the effect screenshot:
Here comes to the full code in C# and VB.NET.
using Spire.Xls; using System.Drawing; using System; namespace Interior { class Program { static void Main(string[] args) { //Create a workbook Workbook workbook = new Workbook(); //Initialize the worksheet Worksheet sheet = workbook.Worksheets[0]; //Specify the version workbook.Version = ExcelVersion.Version2007; //Define the number of the colors int maxColor = Enum.GetValues(typeof(ExcelColors)).Length; //Create a random object Random random = new Random((int)System.DateTime.Now.Ticks); for (int i = 2; i < 40; i++) { //Random backKnownColor ExcelColors backKnownColor = (ExcelColors)(random.Next(1, maxColor / 2)); sheet.Range["A1"].Text = "Color Name"; sheet.Range["B1"].Text = "Red"; sheet.Range["C1"].Text = "Green"; sheet.Range["D1"].Text = "Blue"; //Merge the sheet"E1-K1" sheet.Range["E1:K1"].Merge(); sheet.Range["E1:K1"].Text = "Gradient"; sheet.Range["A1:K1"].Style.Font.IsBold = true; sheet.Range["A1:K1"].Style.Font.Size = 11; //Set the text of color in sheetA-sheetD string colorName = backKnownColor.ToString(); sheet.Range[string.Format("A{0}", i)].Text = colorName; sheet.Range[string.Format("B{0}", i)].Text = workbook.GetPaletteColor(backKnownColor).R.ToString(); sheet.Range[string.Format("C{0}", i)].Text = workbook.GetPaletteColor(backKnownColor).G.ToString(); sheet.Range[string.Format("D{0}", i)].Text = workbook.GetPaletteColor(backKnownColor).B.ToString(); //Merge the sheets sheet.Range[string.Format("E{0}:K{0}", i)].Merge(); //Set the text of sheetE-sheetK sheet.Range[string.Format("E{0}:K{0}", i)].Text = colorName; //Set the interior of the color sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.FillPattern = ExcelPatternType.Gradient; sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.Gradient.BackKnownColor = backKnownColor; sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.Gradient.ForeKnownColor = ExcelColors.White; sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.Gradient.GradientStyle = GradientStyleType.Vertical; sheet.Range[string.Format("E{0}:K{0}", i)].Style.Interior.Gradient.GradientVariant = GradientVariantsType.ShadingVariants1; } //AutoFit Column sheet.AutoFitColumn(1); //Save the file workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003); //Launch the file System.Diagnostics.Process.Start("Sample.xls"); } } }
Imports Spire.Xls Imports System.Drawing Imports System Module Module1 Sub Main() 'Create a workbook Dim workbook As New Workbook() 'Initialize the worksheet Dim sheet As Worksheet = workbook.Worksheets(0) 'Specify the version workbook.Version = ExcelVersion.Version2007 'Define the number of the colors Dim maxColor As Integer = [Enum].GetValues(GetType(ExcelColors)).Length 'Create a random object Dim random As New Random() For i As Integer = 2 To 39 'Random backKnownColor Dim backKnownColor As ExcelColors = DirectCast(random.[Next](1, maxColor \ 2), ExcelColors) sheet.Range("A1").Text = "Color Name" sheet.Range("B1").Text = "Red" sheet.Range("C1").Text = "Green" sheet.Range("D1").Text = "Blue" 'Merge the sheet"E1-K1" sheet.Range("E1:K1").Merge() sheet.Range("E1:K1").Text = "Gradient" sheet.Range("A1:K1").Style.Font.IsBold = True sheet.Range("A1:K1").Style.Font.Size = 11 'Set the text of color in sheetA-sheetD Dim colorName As String = backKnownColor.ToString() sheet.Range(String.Format("A{0}", i)).Text = colorName sheet.Range(String.Format("B{0}", i)).Text = workbook.GetPaletteColor(backKnownColor).R.ToString() sheet.Range(String.Format("C{0}", i)).Text = workbook.GetPaletteColor(backKnownColor).G.ToString() sheet.Range(String.Format("D{0}", i)).Text = workbook.GetPaletteColor(backKnownColor).B.ToString() 'Merge the sheets sheet.Range(String.Format("E{0}:K{0}", i)).Merge() 'Set the text of sheetE-sheetK sheet.Range(String.Format("E{0}:K{0}", i)).Text = colorName 'Set the interior of the color sheet.Range(String.Format("E{0}:K{0}", i)).Style.Interior.FillPattern = ExcelPatternType.Gradient sheet.Range(String.Format("E{0}:K{0}", i)).Style.Interior.Gradient.BackKnownColor = backKnownColor sheet.Range(String.Format("E{0}:K{0}", i)).Style.Interior.Gradient.ForeKnownColor = ExcelColors.White sheet.Range(String.Format("E{0}:K{0}", i)).Style.Interior.Gradient.GradientStyle = GradientStyleType.Vertical sheet.Range(String.Format("E{0}:K{0}", i)).Style.Interior.Gradient.GradientVariant = GradientVariantsType.ShadingVariants1 Next 'AutoFit Column sheet.AutoFitColumn(1) 'Save doc file. workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003) 'Launching the MS Word file. System.Diagnostics.Process.Start("Sample.xls") End Sub End Module
After running the demo, you will find color interior in your 2007 worksheet.
In today's digital age, managing and manipulating Excel files programmatically has become an essential skill for developers. Whether you're building a reporting tool, automating data processing, or enhancing your applications with dynamic data handling, having a robust library at your disposal can make all the difference. Enter Spire.XLS for .NET - a versatile and powerful library that allows you to create, read, write, and edit Excel files seamlessly using C#.
In this article, you will learn how to edit Excel documents effortlessly using C# and Spire.XLS for .NET.
- Read and Write Excel Files in C#
- Apply Styles and Formats to Excel Cells in C#
- Find and Replace Text in Excel in C#
- Add Formulas and Charts to Excel in C#
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
Read and Write Excel Files in C#
One of the most common tasks when working with Excel files in C# is reading and writing data. Spire.XLS for .NET provides the CellRange.Value property, enabling developers to easily retrieve or assign values to individual cells.
The step to read and write an Excel file using C# are as follows:
- Create a Workbook object.
- Load an Excel file from a given file path.
- Get a specific worksheet using the Workbook.Worksheets[] property.
- Get a specific cell using the Worksheet.Range[] property
- Get or set the cell value using the CellRange.Value property.
- Save the workbook to a different Excel file.
- C#
using Spire.Xls; namespace ReadAndWriteExcel { class Program { static void Main(string[] args) { // Create a Workbook object Workbook workbook = new Workbook(); // Load an Excel file workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); // Get a specific worksheet Worksheet worksheet = workbook.Worksheets[0]; // Get a specific cell CellRange cell = worksheet.Range["A1"]; // Read the cell value String text = cell.Value; // Determine if the cell value is "Department" if (text == "Department") { // Update the cell value cell.Value = "Dept."; } // Save the workbook to a different workbook.SaveToFile("ModifyExcel.xlsx", ExcelVersion.Version2016); // Dispose resources workbook.Dispose(); } } }
Apply Styles and Formats to Excel Cells in C#
Styling and formatting Excel documents is an important aspect of creating professional-looking reports. Spire.XLS for .NET offers a variety of APIs within the CellRange class for managing cell styles, fonts, colors, and alignments, as well as adjusting row heights and column widths.
The steps to apply styles and formats to Excel cells are as follows:
- Create a Workbook object.
- Load an Excel file from a given file path.
- Get a specific worksheet using the Workbook.Worksheets[] property.
- Get all located range using the Worksheet.AllocatedRange property.
- Get a specific row using the CellRange.Rows[] property, and set the cell color, text color, text alignment, and row height using the properties under the CellRange object.
- Get a specific column using the CellRange.Columns[] property, and set the column width using the ColumnWidth property under the CellRange object.
- Save the workbook to a different Excel file.
- C#
using Spire.Xls; using System.Drawing; namespace FormatCells { class Program { static void Main(string[] args) { // Create a Workbook object Workbook workbook = new Workbook(); // Load an Excel file workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); // Get a specific worksheet Worksheet worksheet = workbook.Worksheets[0]; // Get all located range from the worksheet CellRange allocatedRange = worksheet.AllocatedRange; // Iterate through the rows for (int rowNum = 0; rowNum < allocatedRange.RowCount; rowNum++) { if(rowNum == 0) { // Apply cell color to the header row allocatedRange.Rows[rowNum].Style.Color = Color.Black; // Change the font color of the header row allocatedRange.Rows[rowNum].Style.Font.Color = Color.White; } // Apply alternate colors to other rows else if (rowNum % 2 == 1) { allocatedRange.Rows[rowNum].Style.Color = Color.LightGray; } else if (rowNum % 2 == 0) { allocatedRange.Rows[rowNum].Style.Color = Color.White; } // Align text to center allocatedRange.Rows[rowNum].HorizontalAlignment = HorizontalAlignType.Center; allocatedRange.Rows[rowNum].VerticalAlignment = VerticalAlignType.Center; // Set the row height allocatedRange.Rows[rowNum].RowHeight = 20; } // Iterate through the columns for (int columnNum = 0; columnNum < allocatedRange.ColumnCount; columnNum++) { // Set the column width if (columnNum > 0) { allocatedRange.Columns[columnNum].ColumnWidth = 10; } } // Save the workbook to a different workbook.SaveToFile("FormatExcel.xlsx", ExcelVersion.Version2016); // Dispose resources workbook.Dispose(); } } }
Find and Replace Text in Excel in C#
The find and replace feature in Excel enhances data accuracy and consistency while significantly improving efficiency. With Spire.XLS for .NET, you can easily locate a cell containing a specific string using the Worksheet.FindString() method and then update the cell value with the CellRange.Value property.
The steps to find and replace text in Excel using C# are as follows:
- Create a Workbook object.
- Load an Excel file from a given file path.
- Get a specific worksheet using the Workbook.Worksheets[] property.
- Find the cell that contains a specified string using the Worksheet.FindString() method.
- Update the cell value using the CellRange.Value property.
- Save the workbook to a different Excel file.
- C#
using Spire.Xls; namespace FindAndReplaceText { class Program { static void Main(string[] args) { // Create a Workbook object Workbook workbook = new Workbook(); // Load an Excel file workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); // Get a specific worksheet Worksheet worksheet = workbook.Worksheets[0]; // Define an array of department names for replacement String[] departments = new String[] { "Sales", "Marketing", "R&D", "HR", "IT", "Finance", "Support" }; // Define an array of placeholders that will be replaced in the Excel sheet String[] placeholders = new String[] { "#dept_one", "#dept_two", "#dept_three", "#dept_four", "#dept_five", "#dept_six", "#dept_seven" }; // Iterate through the placeholder strings for (int i = 0; i < placeholders.Length; i++) { // Find the cell containing the current placeholder string CellRange cell = worksheet.FindString(placeholders[i], false, false); // Replace the text in the found cell with the corresponding department name cell.Text = departments[i]; } // Save the workbook to a different workbook.SaveToFile("ReplaceText.xlsx", ExcelVersion.Version2016); // Dispose resources workbook.Dispose(); } } }
Add Formulas and Charts to Excel in C#
In addition to basic file operations, Spire.XLS for .NET provides a variety of advanced techniques for working with Excel files. These techniques can be used to automate complex tasks, perform calculations, and generate dynamic reports.
The following are the steps to add formulas and create a chart in Excel using C#:
- Create a Workbook object.
- Load an Excel file from a given file path.
- Get a specific worksheet using the Workbook.Worksheets[] property.
- Get a specific cell using the Worksheet.Range[] property.
- Add a formula to the cell using the CellRange.Formula property.
- Add a column chart to the worksheet using the Worksheet.Charts.Add() method.
- Set the chart data range, position, title and other attributes using the methods and properties under the Chart object.
- Save the workbook to a different Excel file.
- C#
using Spire.Xls; namespace AddFormulaAndChart { class Program { static void Main(string[] args) { // Create a Workbook object Workbook workbook = new Workbook(); // Load an Excel file workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); // Get a specific worksheet Worksheet worksheet = workbook.Worksheets[0]; // Get all located range CellRange allocatedRange = worksheet.AllocatedRange; // Iterate through the rows for (int rowNum = 0; rowNum < allocatedRange.RowCount; rowNum++) { if (rowNum == 0) { // Write text in the cell F1 worksheet.Range[rowNum + 1, 6].Text = "Total"; // Apply style to the cell worksheet.Range[rowNum + 1, 6].Style.Font.IsBold = true; worksheet.Range[rowNum + 1, 6].Style.HorizontalAlignment = HorizontalAlignType.Right; } else { // Add formulas to the cells from F2 to F8 worksheet.Range[rowNum + 1, 6].Formula = $"=SUM(B{rowNum + 1}:E{rowNum + 1})"; } } // Add a clustered column chart Chart chart = worksheet.Charts.Add(ExcelChartType.ColumnClustered); // Set data range for the chart chart.DataRange = worksheet.Range["A1:E8"]; chart.SeriesDataFromRange = false; // Set position of the chart chart.LeftColumn = 1; chart.TopRow = 10; chart.RightColumn = 8; chart.BottomRow = 23; // Set and format chart title chart.ChartTitle = "Sales by Department per Quarter"; chart.ChartTitleArea.Size = 13; chart.ChartTitleArea.IsBold = true; // Save the workbook to a different workbook.SaveToFile("AddFormulaAndChart.xlsx", ExcelVersion.Version2016); // Dispose resources 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.
This section aims at providing developers a solution to unlock sheet in Excel workbook with C#, VB.NET via this Excel library Spire.XLS for .NET.
Spire.XLS for .NET enables you to unlock any sheet in Excel file only by one line of key code: Spire.Xls.Worksheet.Unprotect(string password); Besides, as an MS Excel component, Spire.XLS for .NET also enables you to create, read and handle Excel files with fast speed. Below is an Excel file with protected worksheets which will be unlocked in my task.
Since you will use Spire.XLS for .NET, you have to download Spire.XLS for .NET and install it on system. When you create your project, please do not forget to add Spire.XLS.dll as reference from Bin folder. The default path is "..\Spire.XLS\Bin\NET4.0\Spire.XLS.dll". Please note that Spire.XLS for .NET supports .NET Framework 2.0 and above. Here is the whole code for unlocking Excel sheet:
namespace UnlockExcelSheet { class Program { static void Main(string[] args) { //initialize an instance of Workbook Workbook workbook = new Workbook(); //Load an Excel file with protected worksheet workbook.LoadFromFile(@"..\Unlock Excel Worksheet.xlsx"); //get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Unprotect worksheet sheet.Unprotect("iceblue"); //Save the file workbook.SaveToFile("Sample.xlsx",ExcelVersion.Version2010); //Launch the file System.Diagnostics.Process.Start("Sample.xlsx"); } } }
Namespace UnlockExcelSheet Class Program Private Shared Sub Main(args As String()) 'initialize an instance of Workbook Dim workbook As New Workbook() 'Load an Excel file with protected worksheet workbook.LoadFromFile("..\Unlock Excel Worksheet.xlsx") 'get the first worksheet Dim sheet As Worksheet = workbook.Worksheets(0) 'Unprotect worksheet sheet.Unprotect("iceblue") 'Save the file workbook.SaveToFile("Sample.xlsx",ExcelVersion.Version2010) 'Launch the file System.Diagnostics.Process.Start("Sample.xlsx") End Sub End Class End Namespace
After executing above code, you can see that the protected worksheet in the original Excel file has been unlocked, we can edit it also. Please see following image.
In this section, I have introduced the solution to unlock any sheet in Excel file via Spire.XLS for .NET. I hope it can help you. If you have any questions, feedbacks and advice, you can put them on E-iceblue Forum. We will promise a prompt reply.
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:
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"); } } }
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
In C# applications, efficiently converting data between Excel files and DataTables is essential for enhancing data accessibility, analysis, and processing capabilities. By transferring data from Excel to DataTables, developers can leverage the full power of .NET to analyze, transform, and process data, while converting data back to Excel enables easy sharing, reporting, and integration with other systems. This article demonstrates how to use Spire.XLS for .NET to export data from Excel files DataTable and import Data from Datable to Excel files with C# code.
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
Export Data from Excel to DataTable with C#
Spire.XLS for .NET offers the Worksheet.ExportDataTable() method to export data from an entire Excel worksheet to a DataTable object. Additionally, the Worksheet.Range[].ExportDataTable() method allows exporting from a specific cell range to a DataTable. Developers can use the ExportTableOptions class to customize options when exporting data from a cell range. The detailed steps for the exporting are as follows:
- Create an instance of the Workbook class and load an Excel file using the Workbook.LoadFromFile() method.
- Access a worksheet in the Excel file via the Workbook.Worksheets[] property.
- Export the data from the entire worksheet to a DataTable object using the Worksheet.ExportDataTable() method.
- Alternatively:
- Create an instance of ExportTableOptions to specify export options.
- Export data from a specified cell range to a DataTable using the Worksheet.ExportDataTable() method with the ExportTableOptions instance as a parameter.
- Output the DataTable.
- C#
using Spire.Xls; using System.Data; namespace ExcelToDataTable { class Program { static void Main(string[] args) { // Create an instance of Workbook Workbook wb = new Workbook(); // Load the Excel file wb.LoadFromFile("Sample.xlsx"); // Get a worksheet Worksheet sheet = wb.Worksheets[0]; // Export worksheet data to DataTable //DataTable dataTable = sheet.ExportDataTable(); // Or export a specified cell range to DataTable ExportTableOptions options = new ExportTableOptions(); options.ComputedFormulaValue = true; options.ExportColumnNames = false; options.KeepDataFormat = false; options.RenameStrategy = RenameStrategy.Letter; DataTable dataTable = sheet.Range[5, 1, 7, 6].ExportDataTable(options); // Output the column names of the DataTable for (int i = 0; i < dataTable.Columns.Count; i++) { Console.Write(dataTable.Columns[i].ColumnName + "\t"); } Console.WriteLine(); // Output the data rows of the DataTable foreach (DataRow row in dataTable.Rows) { foreach (var item in row.ItemArray) { Console.Write(item + "\t"); } Console.WriteLine(); } } } }
Import Data from DataTable to Excel with C#
Spire.XLS for .NET provides the Worksheet.InsertDataTable(DataTable, colHeaders: bool, firstRow: int, firstColumn: int) method to insert data from a DataTable object into an Excel worksheet. The detailed steps for importing data from a DataTable to Excel are as follows:
- Define the data and create a DataTable object.
- Create a Workbook instance and clear the default worksheets using the Workbook.Worksheets.Clear() method.
- Insert a new worksheet with a specified name using the Workbook.Worksheets.Add(sheetName: string) method.
- Insert the data from the DataTable object to the worksheet using Worksheet.InsertDataTable() method.
- Adjust the formatting as needed.
- Save the workbook using the Workbook.SaveToFile() method.
- C#
using Spire.Xls; using System.Data; namespace DataTableToExcel { class Program { static void Main(string[] args) { // Define a dataset and create an instance of DataTable // Redefine data array with new products and quantities string[,] data = new string[,] { { "Product", "Quantity", "SalesAmount" }, { "Product X", "75", "4500.0" }, { "Product Y", "200", "12000.0" }, { "Product Z", "90", "5400.0" }, { "Product W", "150", "9000.0" }, { "Product Q", "130", "7800.0" }, { "Product R", "85", "5100.0" }, { "Product S", "160", "9600.0" } }; DataTable dataTable = new DataTable(); // Get the number of columns int columnCount = data.GetLength(1); // Add columns to DataTable for (int col = 0; col < columnCount; col++) { dataTable.Columns.Add(data[0, col]); } // Add rows to DataTable for (int row = 1; row < data.GetLength(0); row++) { DataRow dataRow = dataTable.NewRow(); for (int col = 0; col < columnCount; col++) { dataRow[col] = data[row, col]; } dataTable.Rows.Add(dataRow); } // Create an instance of Workbook Workbook workbook = new Workbook(); // Clear default worksheets and add a new worksheet workbook.Worksheets.Clear(); Worksheet sheet = workbook.Worksheets.Add("SalesReport"); // Import DataTable data into the worksheet sheet.InsertDataTable(dataTable, true, 1, 1); // Adjust column widths for better readability for (int i = 1; i <= sheet.AllocatedRange.ColumnCount; i++) { sheet.AutoFitColumn(i); } // Save the workbook to a file workbook.SaveToFile("output/DataTableToExcel.xlsx", FileFormat.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.
The sample demonstrates how to convert Excel workbook to PDF file via Spire.XLS.
Excel radar charts, also known as spider charts or web charts, are used to compare multiple data series in different categories. By plotting data points on a multi-axis chart, radar charts provide a clear and intuitive representation of data balance and skewness. This makes them particularly useful for visualizing performance metrics, market analysis, and other situations where multiple dimensions need to be compared. In this article, you will learn how to create a radar chart in 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
Create a Simple Radar Chart in Excel in C#
Spire.XLS for .NET provides the Worksheet.Charts.Add(ExcelChartType.Radar) method to add a standard radar chart to an Excel worksheet. The following are the detailed steps:
- Create a Workbook instance.
- Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
- Add the chart data to specified cells and set the cell styles.
- Add a simple radar chart to the worksheet using Worksheet.Charts.Add(ExcelChartType.Radar) method.
- Set data range for the chart using Chart.DataRange property.
- Set the position, legend and title of the chart.
- Save the result file using Workbook.SaveToFile() method.
- C#
using Spire.Xls; using System.Drawing; namespace ExcelRadarChart { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Add chart data to specified cells sheet.Range["A1"].Value = "Rating"; sheet.Range["A2"].Value = "Communication"; sheet.Range["A3"].Value = "Experience"; sheet.Range["A4"].Value = "Work Efficiency"; sheet.Range["A5"].Value = "Leadership"; sheet.Range["A6"].Value = "Problem-solving"; sheet.Range["A7"].Value = "Teamwork"; sheet.Range["B1"].Value = "Jonathan"; sheet.Range["B2"].NumberValue = 4; sheet.Range["B3"].NumberValue = 3; sheet.Range["B4"].NumberValue = 4; sheet.Range["B5"].NumberValue = 3; sheet.Range["B6"].NumberValue = 5; sheet.Range["B7"].NumberValue = 5; sheet.Range["C1"].Value = "Ryan"; sheet.Range["C2"].NumberValue = 2; sheet.Range["C3"].NumberValue = 5; sheet.Range["C4"].NumberValue = 4; sheet.Range["C5"].NumberValue = 4; sheet.Range["C6"].NumberValue = 3; sheet.Range["C7"].NumberValue = 3; //Set font styles sheet.Range["A1:C1"].Style.Font.IsBold = true; sheet.Range["A1:C1"].Style.Font.Size = 11; sheet.Range["A1:C1"].Style.Font.Color = Color.White; //Set row height and column width sheet.Rows[0].RowHeight = 20; sheet.Range["A1:C7"].Columns[0].ColumnWidth = 15; //Set cell styles sheet.Range["A1:C1"].Style.Color = Color.DarkBlue; sheet.Range["A2:C7"].Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin; sheet.Range["A2:C7"].Style.Borders[BordersLineType.EdgeBottom].Color = Color.DarkBlue; sheet.Range["B1:C7"].HorizontalAlignment = HorizontalAlignType.Center; sheet.Range["A1:C7"].VerticalAlignment = VerticalAlignType.Center; //Add a radar chart to the worksheet Chart chart = sheet.Charts.Add(ExcelChartType.Radar); //Set position of chart chart.LeftColumn = 4; chart.TopRow = 4; chart.RightColumn = 14; chart.BottomRow = 29; //Set data range for the chart chart.DataRange = sheet.Range["A1:C7"]; chart.SeriesDataFromRange = false; //Set and format chart title chart.ChartTitle = "Employee Performance Appraisal"; chart.ChartTitleArea.IsBold = true; chart.ChartTitleArea.Size = 14; //Set position of chart legend chart.Legend.Position = LegendPositionType.Corner; //Save the result file workbook.SaveToFile("ExcelRadarChart.xlsx", ExcelVersion.Version2016); } } }
Create a Filled Radar Chart in Excel in C#
A filled radar chart is a variation of a standard radar chart, with the difference that the area between each data point is filled with color. The following are the steps to create a filled radar chart using C#:
- Create a Workbook instance.
- Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
- Add the chart data to specified cells and set the cell styles.
- Add a filled radar chart to the worksheet using Worksheet.Charts.Add(ExcelChartType.RadarFilled) method.
- Set data range for the chart using Chart.DataRange property.
- Set the position, legend and title of the chart.
- Save the result file using Workbook.SaveToFile() method.
- C#
using Spire.Xls; using System.Drawing; namespace ExcelRadarChart { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Add chart data to specified cells sheet.Range["A1"].Value = "Rating"; sheet.Range["A2"].Value = "Communication"; sheet.Range["A3"].Value = "Experience"; sheet.Range["A4"].Value = "Work Efficiency"; sheet.Range["A5"].Value = "Leadership"; sheet.Range["A6"].Value = "Problem-solving"; sheet.Range["A7"].Value = "Teamwork"; sheet.Range["B1"].Value = "Jonathan"; sheet.Range["B2"].NumberValue = 4; sheet.Range["B3"].NumberValue = 3; sheet.Range["B4"].NumberValue = 4; sheet.Range["B5"].NumberValue = 3; sheet.Range["B6"].NumberValue = 5; sheet.Range["B7"].NumberValue = 5; sheet.Range["C1"].Value = "Ryan"; sheet.Range["C2"].NumberValue = 2; sheet.Range["C3"].NumberValue = 5; sheet.Range["C4"].NumberValue = 4; sheet.Range["C5"].NumberValue = 4; sheet.Range["C6"].NumberValue = 3; sheet.Range["C7"].NumberValue = 3; //Set font styles sheet.Range["A1:C1"].Style.Font.IsBold = true; sheet.Range["A1:C1"].Style.Font.Size = 11; sheet.Range["A1:C1"].Style.Font.Color = Color.White; //Set row height and column width sheet.Rows[0].RowHeight = 20; sheet.Range["A1:C7"].Columns[0].ColumnWidth = 15; //Set cell styles sheet.Range["A1:C1"].Style.Color = Color.DarkBlue; sheet.Range["A2:C7"].Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin; sheet.Range["A2:C7"].Style.Borders[BordersLineType.EdgeBottom].Color = Color.DarkBlue; sheet.Range["B1:C7"].HorizontalAlignment = HorizontalAlignType.Center; sheet.Range["A1:C7"].VerticalAlignment = VerticalAlignType.Center; //Add a filled radar chart to the worksheet Chart chart = sheet.Charts.Add(ExcelChartType.RadarFilled); //Set position of chart chart.LeftColumn = 4; chart.TopRow = 4; chart.RightColumn = 14; chart.BottomRow = 29; //Set data range for the chart chart.DataRange = sheet.Range["A1:C7"]; chart.SeriesDataFromRange = false; //Set and format chart title chart.ChartTitle = "Employee Performance Appraisal"; chart.ChartTitleArea.IsBold = true; chart.ChartTitleArea.Size = 14; //Set position of chart legend chart.Legend.Position = LegendPositionType.Corner; //Save the result file workbook.SaveToFile("FilledRadarChart.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.
