Insert Excel Worksheets in WPF

2012-06-21 06:32:57 Written by Koohji

Are there multiple choices for creating Excel worksheets in WPF with quick and steady performance? The answer is definitely positive. The post presents different choices for creating Excel worksheets in WPF.

Each solution will be managed within several lines of code; meanwhile the performance will be perfect for any kind of user. All the solution will be built base on Spire.Xls for WPF, which enables developers to fast generate, edit Excel files. Developers can control Excel on cell formatting, page setup, data sort and filter, chart and formulas. Besides, developers can use this component to import data into Excel from database and export data from Excel to database.

Spire.Xls for WPF is always welcome to any kind of trial and evaluation. So now please feel free to download Spire.XLS for WPF and then follow our guide to easily insert Excel worksheets WPF or try other function of Spire.Xls for WPF.

Friendly Reminder:

  • Before we code to insert Excel worksheet in WPF, please add spire.xls dll as reference by Clicking ProjectAdd ReferenceBrowseChoose the folder contains Spire.XLS for WPF → Bin.NET 4.0.
  • Please make sure the namespace-Spire.Xls being imported.
Next we will demonstrate the following choices for creating Excel worksheet.

Step 1: Insert a worksheet to Excel in WPF

In this method, we will insert a worksheet to Excel in WPF by calling Workbook.Worksheet.add(string sheetname) function, please check my code examples.

[C#]
Workbook myWorkbook = new Workbook();
myWorkbook.Worksheets.Add("My New Worksheet");
myWorkbook.SaveToFile("Result.xls");
System.Diagnostics.Process.Start(myWorkbook.FileName);
[VB.NET]
Dim myWorkbook As New Workbook()
myWorkbook.Worksheets.Add("My New Worksheet")
myWorkbook.SaveToFile("Result.xls")
System.Diagnostics.Process.Start(myWorkbook.FileName)

Effective Screenshot shows we have successfully inserted Excel worksheet in WPF.

Insert Excel Worksheet

Step 2: Create empty Excel worksheet in WPF

In this method, we will insert a worksheet to Excel in WPF using Workbook.CreateEmptySheet(string sheetname) function, please check my code examples.

[C#]
Workbook workbook = new Workbook();
workbook.CreateEmptySheet("New Empty Worksheet");
workbook.SaveToFile("Sample.xls");
System.Diagnostics.Process.Start(workbook.FileName);
[VB.NET]
Dim workbook As New Workbook()
workbook.CreateEmptySheet("New Empty Worksheet")
workbook.SaveToFile("Sample.xls")
System.Diagnostics.Process.Start(workbook.FileName)

Effective Screenshot shows we have successfully inserted Excel worksheet in WPF.

Insert Excel Worksheet

Step 3: Insert several worksheet at one time

[C#]
Workbook workbook = new Workbook();
workbook.CreateEmptySheets(6);
workbook.SaveToFile("Sample.xls");
System.Diagnostics.Process.Start(workbook.FileName);
[VB.NET]
Dim workbook As New Workbook()
workbook.CreateEmptySheets(6)
workbook.SaveToFile("Sample.xls")
System.Diagnostics.Process.Start(workbook.FileName)

Five worksheet have been inserted at one time, please check the effective screenshot:

Insert Excel Worksheet

C#: Insert Rows and Columns in Excel

2024-04-12 03:01:00 Written by Koohji

When working with Excel spreadsheets, it is common to add additional rows or columns as your data set grows or the scope of your project expands. By inserting rows and columns, you can quickly modify the structure of your spreadsheet to accommodate new information. In this article, you will learn how to insert rows and columns 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

Insert a Row and a Column in Excel in C#

Spire.XLS for .NET provides the Worksheet.InsertRow(int rowIndex) and Worksheet.InsertColumn(int columnIndex) methods for inserting a blank row and a blank column in an Excel worksheet. The following are the detailed steps:

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Insert a row into the worksheet using Worksheet.InsertRow(int rowIndex) method.
  • Insert a column into the worksheet using Worksheet.InsertColumn(int columnIndex) method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

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

            //Load an Excel document
            workbook.LoadFromFile("input.xlsx");

            //Get a specified worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //Insert a blank row as the 5th row in the worksheet
            worksheet.InsertRow(5);

            //Insert a blank column as the 4th column in the worksheet
            worksheet.InsertColumn(4);

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

C#: Insert Rows and Columns in Excel

Insert Multiple Rows and Columns in Excel in C#

To insert multiple rows and columns into a worksheet, you can use the Worksheet.InsertRow(int rowIndex, int rowCount) and Worksheet.InsertColumn(int columnIndex, int columnCount) methods. The following are detailed steps.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Insert multiple rows into the worksheet using Worksheet.InsertRow(int rowIndex, int rowCount) method.
  • Insert multiple columns into the worksheet using Worksheet.InsertColumn(int columnIndex, int columnCount) method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;

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

            //Load an Excel document
            workbook.LoadFromFile(@"E:\PythonExcel\input1.xlsx");

            //Get a specified worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //Insert three blank rows into the worksheet
            worksheet.InsertRow(5, 3);

            //Insert two blank columns into the worksheet
            worksheet.InsertColumn(4, 2);

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

C#: Insert Rows and Columns 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.

There can be no doubt that image and text are the most basic elements for a PDF document. In most cases, people need to insert images and text in a PDF file. While actually, things are not as easy as that. For example, you want to insert an image to your PDF document, but this image is in another PDF file, you can neither find a same picture from internet nor paste it directly to your own PDF. In such a situation, you have to extract the PDF image first and then, insert the images you want to your PDF.

This article is designed to share a method to extract images and text from PDF document for WPF via Spire.PDF for WPF. Using Spire.PDF for WPF, you can easily and quickly extract the PDF images and text, then, add any images you want to another PDF. Please follow the below steps.

Download Spire.PDF (Spire.Office) and with .NET Framework 2.0 (or above) together. Install and follow the guide below.

Step 1: Create a new project

  • Create a new project in WPF Application
  • Add a button in MainWindow and set the button Content property to be "Run".
  • Add Spire.Pdf.Wpf.dll and System.Drawing as references. After adding the namespaces, you can view the below codes.
[C#]
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.IO;
using System.Drawing.Imaging;

namespace pdfextractwpf
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.IO
Imports System.Drawing.Imaging

Namespace pdfextractwpf
	''' 
	''' Interaction logic for MainWindow.xaml
	''' 
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
	          End Sub
	End Class
End Namespace

Step 2: Extract images and text from PDF document

Load a PDF file from system

[C#]
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();                
            doc.LoadFromFile(@"D:\e-iceblue\Spire.PDF\Demos\Data\Sample2.pdf");
[VB.NET]
	'Create a pdf document.
	Dim doc As New PdfDocument()		
        doc.LoadFromFile("D:\e-iceblue\Spire.PDF\Demos\Data\Sample2.pdf")

Extract images and text from PDF document

[C#]
            StringBuilder buffer = new StringBuilder();
            IList images = new List();

            foreach (PdfPageBase page in doc.Pages)
            {
                buffer.Append(page.ExtractText());
                foreach (System.Drawing.Image image in page.ExtractImages())
                {
                    images.Add(image);
                }
            }

            doc.Close();
[VB.NET]
	Dim buffer As New StringBuilder()
	Dim images As IList(Of System.Drawing.Image) = New List(Of System.Drawing.Image)()

	For Each page As PdfPageBase In doc.Pages
		buffer.Append(page.ExtractText())
		For Each image As System.Drawing.Image In page.ExtractImages()
			images.Add(image)
		Next
	Next

	doc.Close()

Save the extracted images and text.

[C#]
            //save text
            String fileName = "TextInPdf.txt";
            File.WriteAllText(fileName, buffer.ToString());

            //save image
            int index = 0;
            foreach (System.Drawing.Image image in images)
            {
                String imageFileName
                    = String.Format("Image-{0}.png", index++);
                image.Save(imageFileName, ImageFormat.Png);
            }
[VB.NET]
	'save text
	Dim fileName As [String] = "TextInPdf.txt"
	File.WriteAllText(fileName, buffer.ToString())

	'save image
	Dim index As Integer = 0
	For Each image As System.Drawing.Image In images
		Dim imageFileName As [String] = [String].Format("Image-{0}.png", System.Math.Max(System.Threading.Interlocked.Increment(index),index - 1))
		image.Save(imageFileName, ImageFormat.Png)
	Next

Step 3: Insert the extracted image to a newly built PDF file

Create a new PDF document and add a page in it

[C#]
            PdfDocument newDoc = new PdfDocument();
            PdfPageBase newPage = newDoc.Pages.Add();
[VB.NET]
	Dim newDoc As New PdfDocument()
        Dim newPage As PdfPageBase = newDoc.Pages.Add()

Draw the PDF text. And insert the extracted the third image in the newly built PDF document.

[C#]
            newPage.Canvas.DrawString("Extract PDF images & text and insert an extracted image to a newly built PDF",
                                   new PdfFont(PdfFontFamily.Helvetica, 14.5f),
                                   new PdfSolidBrush(new PdfRGBColor(0,100,200)),
                                   10, 40);
            PdfImage img = PdfImage.FromImage(images[2]);
            float width = img.Width * 0.75f;
            float height = img.Height * 0.75f;
            float x = (newPage.Canvas.ClientSize.Width - width) / 2;

            newPage.Canvas.DrawImage(img, x, 100, width, height);
[VB.NET]
	newPage.Canvas.DrawString("Extract PDF images & text and insert an extracted image to a newly built PDF", 
                                    New PdfFont(PdfFontFamily.Helvetica, 14.5F), 
                                    New PdfSolidBrush(New PdfRGBColor(0, 100, 200)), 10, 40)
	Dim img As PdfImage = PdfImage.FromImage(images(2))
	Dim width As Single = img.Width * 0.75F
	Dim height As Single = img.Height * 0.75F
	Dim x As Single = (newPage.Canvas.ClientSize.Width - width) / 2
          newPage.Canvas.DrawImage(img, x, 100, width, height)

Save and launch the PDF file

[C#]
            newDoc.SaveToFile("Image.pdf");
            newDoc.Close();
            System.Diagnostics.Process.Start("Image.pdf");
[VB.NET]
	newDoc.SaveToFile("Image.pdf")
	newDoc.Close()
	System.Diagnostics.Process.Start("Image.pdf")

Effecive Screenshot:

>Read PDF Text and Images

Spire.PDF for WPF allows its users not only to extract images and text from PDF document, but also can save the images to the most popular formats such as .PNG, JPG, BMP, GIF and so on. Click to know more

page 287