Excel spreadsheet library for C#/VB.NET

ExpertXls Excel Spreadsheet Library for .NET

Create Excel Spreadsheets in ASP.NET / C#

Adding Images Using ExpertXls Excel Library for .NET

This sample shows how to add images to a worksheet. An image can be added at real size, scaled in width and height by a specified percentage or inside a specified range.
To create the Excel workbook first select the format of the generated workbook and press the Create Workbook button. The Excel workbook will be created on the server and sent as an attachment to the browser. You will be prompted to open the generated workbook in an external viewer. ExpertXls library can generate both XLS and XLSX files.
Workbook Format:
Create Workbook Button Create Excel Workbook
Source Code:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Drawing;
using ExpertXls.ExcelLib;

public partial class ImagesDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void lnkBtnCreateWorkbook_Click(object sender, EventArgs e)
    {
        // get the Excel workbook format
        ExcelWorkbookFormat workbookFormat = radioXlsFormat.Checked ? ExcelWorkbookFormat.Xls_2003 : ExcelWorkbookFormat.Xlsx_2007;

        // create the workbook in the desired format with a single worksheet
        ExcelWorkbook workbook = new ExcelWorkbook(workbookFormat);

        // set the license key before saving the workbook
        //workbook.LicenseKey = "your license key here";

        // set workbook description properties
        workbook.DocumentProperties.Subject = "Images demo";
        workbook.DocumentProperties.Comments = "Add images to an Excel worksheet using ExpertXls Excel library for .NET";

        #region CREATE CUSTOM WORKBOOK STYLES

        #region Add a style used for the cells in the worksheet title area

        ExcelCellStyle titleStyle = workbook.Styles.AddStyle("WorksheetTitleStyle");
        // center the text in the title area
        titleStyle.Alignment.HorizontalAlignment = ExcelCellHorizontalAlignmentType.Center;
        titleStyle.Alignment.VerticalAlignment = ExcelCellVerticalAlignmentType.Center;
        // set the title area borders
        titleStyle.Borders[ExcelCellBorderIndex.Bottom].Color = Color.Green;
        titleStyle.Borders[ExcelCellBorderIndex.Bottom].LineStyle = ExcelCellLineStyle.Medium;
        titleStyle.Borders[ExcelCellBorderIndex.Top].Color = Color.Green;
        titleStyle.Borders[ExcelCellBorderIndex.Top].LineStyle = ExcelCellLineStyle.Medium;
        titleStyle.Borders[ExcelCellBorderIndex.Left].Color = Color.Green;
        titleStyle.Borders[ExcelCellBorderIndex.Left].LineStyle = ExcelCellLineStyle.Medium;
        titleStyle.Borders[ExcelCellBorderIndex.Right].Color = Color.Green;
        titleStyle.Borders[ExcelCellBorderIndex.Right].LineStyle = ExcelCellLineStyle.Medium;
        if (workbookFormat == ExcelWorkbookFormat.Xls_2003)
        {
            // set the solid fill for the title area range with a custom color
            titleStyle.Fill.FillType = ExcelCellFillType.SolidFill;
            titleStyle.Fill.SolidFillOptions.BackColor = Color.FromArgb(255, 255, 204);
        }
        else
        {
            // set the gradient fill for the title area range with a custom color
            titleStyle.Fill.FillType = ExcelCellFillType.GradientFill;
            titleStyle.Fill.GradientFillOptions.Color1 = Color.FromArgb(255, 255, 204);
            titleStyle.Fill.GradientFillOptions.Color2 = Color.White;
        }
        // set the title area font 
        titleStyle.Font.Size = 14;
        titleStyle.Font.Bold = true;
        titleStyle.Font.UnderlineType = ExcelCellUnderlineType.Single;



        #endregion

        #region Add a style used for text messages

        ExcelCellStyle textMessageStyle = workbook.Styles.AddStyle("TextMessageStyle");
        textMessageStyle.Font.Size = 10;
        textMessageStyle.Font.Bold = true;
        textMessageStyle.Alignment.VerticalAlignment = ExcelCellVerticalAlignmentType.Center;
        textMessageStyle.Fill.FillType = ExcelCellFillType.SolidFill;
        textMessageStyle.Fill.SolidFillOptions.BackColor = Color.FromArgb(204, 204, 255);
        textMessageStyle.Borders[ExcelCellBorderIndex.Bottom].LineStyle = ExcelCellLineStyle.Thin;
        textMessageStyle.Borders[ExcelCellBorderIndex.Top].LineStyle = ExcelCellLineStyle.Thin;
        textMessageStyle.Borders[ExcelCellBorderIndex.Left].LineStyle = ExcelCellLineStyle.Thin;
        textMessageStyle.Borders[ExcelCellBorderIndex.Right].LineStyle = ExcelCellLineStyle.Thin;

        #endregion

        #endregion

        // get the first worksheet in the workbook
        ExcelWorksheet worksheet = workbook.Worksheets[0];

        // set the default worksheet name
        worksheet.Name = "Images Demo";

        #region WORKSHEET PAGE SETUP

        // set worksheet paper size and orientation, margins, header and footer
        worksheet.PageSetup.PaperSize = ExcelPagePaperSize.PaperA4;
        worksheet.PageSetup.Orientation = ExcelPageOrientation.Portrait;
        worksheet.PageSetup.LeftMargin = 1;
        worksheet.PageSetup.RightMargin = 1;
        worksheet.PageSetup.TopMargin = 1;
        worksheet.PageSetup.BottomMargin = 1;

        // add header and footer

        //display a logo image in the left part of the header
        string imagesPath = System.IO.Path.Combine(Server.MapPath("~"), @"Images");
        System.Drawing.Image logoImg = System.Drawing.Image.FromFile(System.IO.Path.Combine(imagesPath, "logo.jpg"));
        worksheet.PageSetup.LeftHeaderFormat = "&G";
        worksheet.PageSetup.LeftHeaderPicture = logoImg;
        // display worksheet name in the right part of the header
        worksheet.PageSetup.RightHeaderFormat = "&A";

        // add worksheet header and footer
        // display the page number in the center part of the footer
        worksheet.PageSetup.CenterFooterFormat = "&P";
        // display the workbook file name in the left part of the footer
        worksheet.PageSetup.LeftFooterFormat = "&F";
        // display the current date in the right part of the footer
        worksheet.PageSetup.RightFooterFormat = "&D";

        #endregion

        #region WRITE THE WORKSHEET TOP TITLE

        // merge the cells in the range to create the title area 
        worksheet["A2:G3"].Merge();
        // gets the merged range containing the top left cell of the range
        ExcelRange titleRange = worksheet["A2"].MergeArea;
        // set the text of title area
        worksheet["A2"].Text = "Adding Images to an Excel Worksheet";

        // set a row height of 18 points for each row in the range
        titleRange.RowHeightInPoints = 18;
        // set the worksheet top title style
        titleRange.Style = titleStyle;

        #endregion

        string demoImagesPath = System.IO.Path.Combine(Server.MapPath("~"), @"Images");
        System.Drawing.Image demoImage = System.Drawing.Image.FromFile(System.IO.Path.Combine(imagesPath, "demo_250x300.jpg"));

        #region Add an image at real size

        worksheet[5, 1, 5, 7].Merge();
        worksheet[5, 1, 5, 7].Style = textMessageStyle;
        worksheet[5, 1, 5, 7].RowHeightInPoints = 25;
        worksheet[5, 1].Value = "Add an image at real size :";

        // add an image specifing the top left corner
        ExcelPicture demoExcelPicture = worksheet.Pictures.AddPicture(1, 7, demoImage);

        int leftColumnIndex = demoExcelPicture.LeftColumnIndex;
        int topRowIndex = demoExcelPicture.TopRowIndex;
        int rightColumnIndex = demoExcelPicture.RightColumnIndex;
        int bottomRowIndex = demoExcelPicture.BottomRowIndex;

        string excelPictureSumary = String.Format("Left Column: {0}, Top Row: {1}, Right Column: {2}, Bottom Row: {3}",
            leftColumnIndex, topRowIndex, rightColumnIndex, bottomRowIndex);

        ExcelRange summaryTextRange = worksheet[bottomRowIndex + 1, 1, bottomRowIndex + 1, 7];
        summaryTextRange.Merge();
        summaryTextRange.Style.Fill.FillType = ExcelCellFillType.SolidFill;
        summaryTextRange.Style.Fill.SolidFillOptions.BackColor = Color.LightBlue;
        summaryTextRange.Style.Font.Bold = true;

        worksheet[bottomRowIndex + 1, 1].Value = excelPictureSumary;

        #endregion

        #region Add an image scaled at specified percentage

        worksheet[bottomRowIndex + 4, 1, bottomRowIndex + 4, 7].Merge();
        worksheet[bottomRowIndex + 4, 1, bottomRowIndex + 4, 7].Style = textMessageStyle;
        worksheet[bottomRowIndex + 4, 1, bottomRowIndex + 4, 7].RowHeightInPoints = 25;
        worksheet[bottomRowIndex + 4, 1].Value = "Add an image scaled at 75% :";

        ExcelPicture demoScaledExcelPicture = worksheet.Pictures.AddPicture(1, bottomRowIndex + 6, demoImage, 75, 75);

        leftColumnIndex = demoScaledExcelPicture.LeftColumnIndex;
        topRowIndex = demoScaledExcelPicture.TopRowIndex;
        rightColumnIndex = demoScaledExcelPicture.RightColumnIndex;
        bottomRowIndex = demoScaledExcelPicture.BottomRowIndex;

        excelPictureSumary = String.Format("Left Column: {0}, Top Row: {1}, Right Column: {2}, Bottom Row: {3}",
            leftColumnIndex, topRowIndex, rightColumnIndex, bottomRowIndex);

        summaryTextRange = worksheet[bottomRowIndex + 1, 1, bottomRowIndex + 1, 7];
        summaryTextRange.Merge();
        summaryTextRange.Style.Fill.FillType = ExcelCellFillType.SolidFill;
        summaryTextRange.Style.Fill.SolidFillOptions.BackColor = Color.LightBlue;
        summaryTextRange.Style.Font.Bold = true;

        worksheet[bottomRowIndex + 1, 1].Value = excelPictureSumary;

        #endregion

        #region Add an image in a specified range

        worksheet[bottomRowIndex + 4, 1, bottomRowIndex + 4, 7].Merge();
        worksheet[bottomRowIndex + 4, 1, bottomRowIndex + 4, 7].Style = textMessageStyle;
        worksheet[bottomRowIndex + 4, 1, bottomRowIndex + 4, 7].RowHeightInPoints = 25;
        worksheet[bottomRowIndex + 4, 1].Value = "Add an image in a specified range - Aspect ratio is not be preserved :";

        ExcelPicture demoRangeExcelPicture = worksheet.Pictures.AddPicture(1, bottomRowIndex + 6, 5, bottomRowIndex + 28, demoImage);

        leftColumnIndex = demoRangeExcelPicture.LeftColumnIndex;
        topRowIndex = demoRangeExcelPicture.TopRowIndex;
        rightColumnIndex = demoRangeExcelPicture.RightColumnIndex;
        bottomRowIndex = demoRangeExcelPicture.BottomRowIndex;

        excelPictureSumary = String.Format("Left Column: {0}, Top Row: {1}, Right Column: {2}, Bottom Row: {3}",
            leftColumnIndex, topRowIndex, rightColumnIndex, bottomRowIndex);

        summaryTextRange = worksheet[bottomRowIndex + 1, 1, bottomRowIndex + 1, 7];
        summaryTextRange.Merge();
        summaryTextRange.Style.Fill.FillType = ExcelCellFillType.SolidFill;
        summaryTextRange.Style.Fill.SolidFillOptions.BackColor = Color.LightBlue;
        summaryTextRange.Style.Font.Bold = true;

        worksheet[bottomRowIndex + 1, 1].Value = excelPictureSumary;

        #endregion

        // Save the Excel document in the current HTTP response stream

        string outFileName = workbookFormat == ExcelWorkbookFormat.Xls_2003 ? "ImagesDemo.xls" : "ImagesDemo.xlsx";

        System.Web.HttpResponse httpResponse = System.Web.HttpContext.Current.Response;

        // Prepare the HTTP response stream for saving the Excel document

        // Clear any data that might have been previously buffered in the output stream
        httpResponse.Clear();

        // Set output stream content type for Excel 97-2003 (.xls) or Excel 2007-2013 (.xlsx)
        if (workbookFormat == ExcelWorkbookFormat.Xls_2003)
            httpResponse.ContentType = "Application/x-msexcel";
        else
            httpResponse.ContentType = "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        // Add the HTTP header to announce the Excel document either as an attachment or inline
        httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", outFileName));

        // Save the workbook to the current HTTP response output stream
        // and close the workbook after save to release all the allocated resources
        try
        {
            workbook.Save(httpResponse.OutputStream);
        }
        catch (Exception ex)
        {
            // report any error that might occur during save
            Session["ErrorMessage"] = ex.Message;
            Response.Redirect("ErrorPage.aspx");
        }
        finally
        {
            // close the workbook and release the allocated resources
            workbook.Close();

            #region Dispose the Image object

            if (logoImg != null)
                logoImg.Dispose();

            #endregion
        }

        // End the response and finish the execution of this page
        httpResponse.End();
    }
}

ExpertXls Excel Spreadsheet Library for .NET