page 315

Images are highly effective in conveying thoughts and ideas. Sometimes, you may need to insert images into an Excel report so that audiences can grasp your intentions quickly and clearly. In this article, you will learn how to insert image into Excel 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

Insert Image from Disk into Excel in C# and VB.NET

The following are the steps to insert an image from disk into Excel:

  • Initialize a Workbook instance.
  • Get the desired worksheet using Workbook.Worksheets[sheetIndex] property.
  • Insert an image into the worksheet using the Worksheet.Pictures.Add() method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace InsertImageInExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize a Workbook instance
            Workbook workbook = new Workbook();
            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Insert image into the worksheet
            sheet.Pictures.Add(1, 1, @"E:\work\sample.jpg");

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

C#/VB.NET: Insert Images into Excel

Insert Web Image from a URL into Excel in C# and VB.NET

The following are the steps to insert a web image from a URL into Excel:

  • Initialize a Workbook instance.
  • Get the desired worksheet using Workbook.Worksheets[sheetIndex] property.
  • Initialize a WebClient instance, then download the web image as a byte array from the specified URL using WebClient.DownloadData(urlAddress) method.
  • Initialize a MemoryStream instance from the byte array.
  • Create an Image object from the memory stream then insert it into the worksheet using Worksheet.Pictures.Add() method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;
using System.Drawing;
using System.IO;
using System.Net;

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

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

            //Specify the image URL
            string URL = "https://www.e-iceblue.com/downloads/demo/Logo.png";

            //Initialize a WebClient instance
            WebClient webClient = new WebClient();
            //Download the image as a byte array from the URL 
            byte[] imageData = webClient.DownloadData(URL);

            //Initialize a MemoryStream instance from the byte array
            MemoryStream objImage = new MemoryStream(imageData);

            //Create an Image object from the memory stream
            Image image = Image.FromStream(objImage);

            //Insert the image into the worksheet
            sheet.Pictures.Add(3, 2, image);

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

C#/VB.NET: Insert Images into 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.

A pie chart is a circular chart for visually representation of data. It divides a circular statistical graph into sectors or slices and each sector represents a specific portion of the total percentage. In this article, you will learn how to programmatically create a pie chart in Excel 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 Pie Chart in Excel

The detailed steps are as follows:

  • Create a Workbook instance.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Add some data to specified cells and set the cell styles and borders.
  • Add a pie chart to the worksheet using Worksheet.Charts.Add(ExcelChartType.Pie) method.
  • Set data range for the chart using Chart.DataRange property.
  • Set the position and title of the chart.
  • Get a specified series in the chart and set category labels and values for the series using ChartSerie.CategoryLabels and ChartSerie.Values properties.
  • Show data labels for data points by setting the ChartSerie.DataPoints.DefaultDataPoint.DataLabels.HasValue property as true.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;
using Spire.Xls.Charts;
using System.Drawing;

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

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

            //Set sheet name
            sheet.Name = "Chart data";

            //Add data to specified cells
            sheet.Range["A1"].Value = "Year";
            sheet.Range["A2"].Value = "2002";
            sheet.Range["A3"].Value = "2003";
            sheet.Range["A4"].Value = "2004";
            sheet.Range["A5"].Value = "2005";

            sheet.Range["B1"].Value = "Sales";
            sheet.Range["B2"].NumberValue = 4000;
            sheet.Range["B3"].NumberValue = 6000;
            sheet.Range["B4"].NumberValue = 7000;
            sheet.Range["B5"].NumberValue = 8500;

            //Set cell styles
            sheet.Range["A1:B1"].Style.Font.IsBold = true;
            sheet.Range["A1:B1"].Style.KnownColor = ExcelColors.Black;
            sheet.Range["A1:B1"].Style.Font.Color = Color.White;
            sheet.Range["A1:B5"].Style.HorizontalAlignment = HorizontalAlignType.Center;
            sheet.Range["A1:B5"].Style.VerticalAlignment = VerticalAlignType.Center;

            //Set number format
            sheet.Range["B2:C5"].Style.NumberFormat = "\"$\"#,##0";

            //Set cell borders
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeTop].Color = Color.FromArgb(0, 0, 128);
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeBottom].Color = Color.FromArgb(0, 0, 128);
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeLeft].Color = Color.FromArgb(0, 0, 128);
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeRight].Color = Color.FromArgb(0, 0, 128);
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;

            //Add a pie chart to the worksheet
            Chart chart = sheet.Charts.Add(ExcelChartType.Pie);

            //Set data range for the chart
            chart.DataRange = sheet.Range["B2:B5"];
            chart.SeriesDataFromRange = false;

            //Set position of the chart
            chart.LeftColumn = 1;
            chart.TopRow = 7;
            chart.RightColumn = 9;
            chart.BottomRow = 28;

            //Set and format chart title
            chart.ChartTitle = "Sales by Year";
            chart.ChartTitleArea.IsBold = true;
            chart.ChartTitleArea.Size = 14;

            // Get a specified series in the chart
            ChartSerie cs = chart.Series[0];

            //Set category labels for the series
            cs.CategoryLabels = sheet.Range["A2:A5"];

            //Set values for the series
            cs.Values = sheet.Range["B2:B5"];

            // Show data labels for data points
            cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = true;

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

C#/VB.NET: Create a Pie Chart 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.

C#/VB.NET: Create a Table in Word

2022-08-19 08:42:00 Written by Administrator

In MS Word, the tables can organize and present data in rows and columns, which makes the information easier to understand and analyze. In this article, you will learn how to programmatically create a table with data in a Word document using Spire.Doc for .NET.

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

Create a Simple Table in Word

Below are some of the core classes and methods provided by Spire.Doc for .NET for creating and formatting tables in Word.

Name Description
Table Class Represents a table in a Word document.
TableRow Class Represents a row in a table.
TableCell Class Represents a specific cell in a table.
Section.AddTbale() Method Adds a new table to the specified section.
Table.ResetCells() Method Resets row number and column number.
Table.Rows Property Gets the table rows.
TableRow.Height Property Sets the height of the specified row.
TableRow.Cells Property Returns the cells collection.
TableRow.RowFormat Property Gets the format of the specified row.

The detailed steps are as follows

  • Create a Document object and add a section to it.
  • Prepare the data for the header row and other rows, storing them in a one-dimensional string array and a two-dimensional string array respectively.
  • Add a table to the section using Section.AddTable() method.
  • Insert data to the header row, and set the row formatting, including row height, background color, and text alignment.
  • Insert data to the rest of the rows and apply formatting to these rows.
  • Save the document to another file using Document.SaveToFile() method.
  • C#
  • VB.NET
using System;
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace WordTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();
            //Add a section
            Section s = doc.AddSection();

            //Define the data for the table
            String[] Header = { "Date", "Description", "Country", "On Hands", "On Order" };
            String[][] data = {
                                  new String[]{ "08/07/2021","Dive kayak","United States","24","16"},
                                  new String[]{ "08/07/2021","Underwater Diver Vehicle","United States","5","3"},
                                  new String[]{ "08/07/2021","Regulator System","Czech Republic","165","216"},
                                  new String[]{ "08/08/2021","Second Stage Regulator","United States","98","88"},
                                  new String[]{ "08/08/2021","Personal Dive Sonar","United States","46","45"},
                                  new String[]{ "08/09/2021","Compass Console Mount","United States","211","300"},
                                  new String[]{ "08/09/2021","Regulator System","United Kingdom","166","100"},
                                  new String[]{ "08/10/2021","Alternate Inflation Regulator","United Kingdom","47","43"},
                              };
            //Add a table
            Table table = s.AddTable(true);
            table.ResetCells(data.Length + 1, Header.Length);

            //Set the first row as table header
            TableRow FRow = table.Rows[0];
            FRow.IsHeader = true;

            //Set the height and color of the first row
            FRow.Height = 23;
            FRow.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.LightSeaGreen;
            for (int i = 0; i < Header.Length; i++)
            {
                //Set alignment for cells 
                Paragraph p = FRow.Cells[i].AddParagraph();
                FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                p.Format.HorizontalAlignment = HorizontalAlignment.Center;

                //Set data format
                TextRange TR = p.AppendText(Header[i]);
                TR.CharacterFormat.FontName = "Calibri";
                TR.CharacterFormat.FontSize = 12;
                TR.CharacterFormat.Bold = true;
            }

            //Add data to the rest of rows and set cell format
            for (int r = 0; r < data.Length; r++)
            {
                TableRow DataRow = table.Rows[r + 1];
                DataRow.Height = 20;
                for (int c = 0; c < data[r].Length; c++)
                {
                    DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    Paragraph p2 = DataRow.Cells[c].AddParagraph();
                    TextRange TR2 = p2.AppendText(data[r][c]);
                    p2.Format.HorizontalAlignment = HorizontalAlignment.Center;

                    //Set data format
                    TR2.CharacterFormat.FontName = "Calibri";
                    TR2.CharacterFormat.FontSize = 11;
                }
            }

            //Save the document
            doc.SaveToFile("WordTable.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Create a Table in Word

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.

page 315