Creating advanced Excel 2007 Reports on Server

Recently I was looking for an Advance tool through which I can generate complex Excel Reports. And after going through many tools I found EP Plus. For further details see this link. Through this tool we can easily create reports with charts, graphs and other drawing objects. I have planned to shared few samples with the community, so if any one is interested in using this library he will get a good kick start.

In this sample application I have tried to explain that how you can generate a report using DataTable. I also demonstrated how to use different formatting options and formulas.

So, here is the code:-

/// <summary>
/// Creates the data table.
/// </summary>
/// <returns>DataTable</returns>
private static DataTable CreateDataTable()
{
    DataTable dt = new DataTable();
    for (int i = 0; i < 10; i++)
    {
        dt.Columns.Add(i.ToString());
    }
 
    for (int i = 0; i < 10; i++)
    {
        DataRow dr = dt.NewRow();
        foreach (DataColumn dc in dt.Columns)
        {
            dr[dc.ToString()] = i;
        }
 
        dt.Rows.Add(dr);
    }
    return dt;
}
 
private void button1_Click(object sender, EventArgs e)
{
    using (ExcelPackage p = new ExcelPackage())
    {
        //Here setting some document properties
        p.Workbook.Properties.Author = "Zeeshan Umar";
        p.Workbook.Properties.Title = "Office Open XML Sample";
 
        //Create a sheet
        p.Workbook.Worksheets.Add("Sample WorkSheet");
        ExcelWorksheet ws = p.Workbook.Worksheets[1];
        ws.Name = "Sample Worksheet"; //Setting Sheet's name
        ws.Cells.Style.Font.Size= 11; //Default font size for whole sheet
        ws.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet
 
 
        DataTable dt = CreateDataTable(); //My Function which generates DataTable
 
        //Merging cells and create a center heading for out table
        ws.Cells[1, 1].Value = "Sample DataTable Export";
        ws.Cells[1, 1, 1, dt.Columns.Count].Merge = true;
        ws.Cells[1, 1, 1, dt.Columns.Count].Style.Font.Bold = true;
        ws.Cells[1, 1, 1, dt.Columns.Count].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
 
        int colIndex = 1;
        int rowIndex = 2;
 
        foreach (DataColumn dc in dt.Columns) //Creating Headings
        {
            var cell = ws.Cells[rowIndex, colIndex];
 
            //Setting the background color of header cells to Gray
            var fill = cell.Style.Fill;
            fill.PatternType = ExcelFillStyle.Solid;
            fill.BackgroundColor.SetColor(Color.Gray);
 
 
            //Setting Top/left,right/bottom borders.
            var border = cell.Style.Border;
            border.Bottom.Style = 
                border.Top.Style = 
                border.Left.Style = 
                border.Right.Style = ExcelBorderStyle.Thin;
 
            //Setting Value in cell
            cell.Value = "Heading " + dc.ColumnName;
 
            colIndex++;
        }
 
        foreach (DataRow dr in dt.Rows) // Adding Data into rows
        {
            colIndex = 1;
            rowIndex++;
            foreach (DataColumn dc in dt.Columns)
            {
                var cell = ws.Cells[rowIndex, colIndex];
                //Setting Value in cell
                cell.Value = Convert.ToInt32(dr[dc.ColumnName]);
 
                //Setting borders of cell
                var border = cell.Style.Border;
                border.Left.Style =
                    border.Right.Style = ExcelBorderStyle.Thin;
                colIndex++;
            }
        }
 
        colIndex = 0;
        foreach (DataColumn dc in dt.Columns) //Creating Headings
        {
            colIndex++;
            var cell = ws.Cells[rowIndex, colIndex];
 
            //Setting Sum Formula
            cell.Formula = "Sum("+ 
                            ws.Cells[3, colIndex].Address+
                            ":"+
                            ws.Cells[rowIndex-1, colIndex].Address+
                            ")";
 
            //Setting Background fill color to Gray
            cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
            cell.Style.Fill.BackgroundColor.SetColor(Color.Gray);
        }
 
        //Generate A File with Random name
        Byte[] bin = p.GetAsByteArray();
        string file = "d:\\" + Guid.NewGuid().ToString() + ".xlsx";
        File.WriteAllBytes(file, bin);
    }
}

Here is the snapshot of Excel File which is created through above code:-

Hopefully this will be useful for you, keep posting your comments.For further details and download see EP Plus home page.

Export to Excel in .Net

There is a wonderful open source Excel Library through which you can easily convert DataSet into multi sheet excel file, just by one line of code like this:-

ExcelXmlWorkbook sheet = ExcelXmlWorkbook.DataSetToWorkbook(sourceDataSet);

Also adding a sample code which will really help you to create reports:-

 
private void YougeshSample()
{
    DataTable dt = CreateDataTable();
 
    ExcelXmlWorkbook book = new ExcelXmlWorkbook();
    book.Properties.Author = "Zeeshan Umar";
    book.Properties.Company = "Sample Company";
    book.Properties.Title = "Sample Title";
    book.Properties.Subject = "Subject";
 
    Worksheet ws = book[0];
    ws.Name = "Sample Sheet Name"; //Sheet Name
    ws.Font.Name = "Calibri";//Setting font for all sheet
    ws.Font.Size = 11;
 
    int rowIndex = 0;
    Row row;
    row = ws[rowIndex++];
 
    int colIndex = 0;
    foreach (DataColumn dc in dt.Columns) //Creating Headings
    {
        row[colIndex].Value = "Heading " + dc.ColumnName;
        row[colIndex].Border.Sides = BorderSides.All;
        row[colIndex].Style.Interior.Color = Color.LightGray;
        colIndex++;
    }
 
    foreach (DataRow dr in dt.Rows) // Adding Data into rows
    {
        colIndex = 0;
        row = ws[rowIndex++];
        foreach (DataColumn dc in dt.Columns)
        {
            row[colIndex].Value = Convert.ToInt32(dr[dc.ColumnName]);
            row[colIndex].Border.Sides = BorderSides.Left | BorderSides.Right;
            setIntegerFormat(row[colIndex]);
            colIndex++;
        }
    }
 
    row = ws[rowIndex++];
    colIndex = 0;
    foreach (DataColumn dc in dt.Columns) //Adding summ formula for last row
    {
        row[colIndex].Value = FormulaHelper.Formula("sum", 
            new Range(ws[colIndex, 1], ws[colIndex, 9]));
        row[colIndex].Border.Sides = BorderSides.All;
        row[colIndex].Style.Interior.Color = Color.LightGray;
        colIndex++;
    }
 
    string s = "c:\\" + Guid.NewGuid().ToString() + ".xml";
    book.Export(s);
}
 
private static DataTable CreateDataTable()
{
    DataTable dt = new DataTable();
    for (int i = 0; i < 300; i++)
    {
        dt.Columns.Add(i.ToString());
    }
    for (int i = 0; i < 10; i++)
    {
        DataRow dr = dt.NewRow();
        foreach (DataColumn dc in dt.Columns)
        {
 
            dr[dc.ToString()] = i;
        }
        dt.Rows.Add(dr);
    }
    return dt;
}
 
private void setIntegerFormat(Cell cell)
{
    cell.DisplayFormat = DisplayFormatType.Custom;
    cell.CustomFormatString = "#,##0";
}
 
private void setDateFormat(Cell cell)
{
    cell.DisplayFormat = DisplayFormatType.GeneralDate;
    cell.CustomFormatString = "dd\\-mmm\\-yyyy\\ hh:mm";
}

For further details see this link:-
A Very Easy to Use Excel XML Import-Export Library

To download latest version of library see this link:-
Excel Xml Library 2.45 released

How do disable back button in browser

Generally there are cases when we want to disable back button in browser. We have multiple options to disable back button in browser. Here are the few:-

Java Script Way
We can use following java script to prevent back button:-
<script type = "text/javascript" >
function disableBackButton()
{ 
window.history.forward();
}
setTimeout("disableBackButton()", 0);
window.onunload=function()
{
null
};
</script>

HTML Way
We can also add Meta Tags in Head Section like this:-
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />

If you want to do above approach through code. Here is the trick:-

HtmlMeta pragma = new HtmlMeta();

pragma.HttpEquiv = "Pragma";

pragma.Content = "no-cache";

Page.Header.Controls.Add(pragma);

 

HtmlMeta expires = new HtmlMeta();

expires.HttpEquiv = "Expires";

expires.Content = "-1";

Page.Header.Controls.Add(expires);


ASP.Net Way
In ASP.Net we can use Cache to disable back button like this:-

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));

Response.Cache.SetNoStore();

Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

A potentially dangerous Request.Form value was detected from the client


Above error comes because by default ASP.Net blocks the possible Script Injection request. e.g. if user type <script>alert('yes');</script> in your text box and when you display the text in text box, this java script will be executed instead of displaying text.

To resolve this problem you need to keep few things in mind:-

1- We can remove HTML Tags from TextBoxes with a simple regular expression filter like this:-
<asp:textbox id="txtSecureTextBox" runat="server" onblur="this.value = this.value.replace(/&lt;\/?[^>]+>/gi, '');">

2- Add ValidateRequest="false" in your Page directive line incase you want to disable this on single page.
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false"/>

3- Incase you want to disable validation through out the site then you can do it in your web.config file like this:-
<configuration>  
  <system.web>  
    <pages validateRequest="false" />  
  </system.web> 
</configuration>

4- Use HTMLEncode whenever you are displaying unsafe contents in labels like this:-
Label1.Text = Server.HtmlEncode(TextBox1.Text) 

For further details see Request Validation - Preventing Script Attacks.

Generate High quality Thumbnail Images and Maintain Aspect Ratio

I was looking up for a simple thumbnail generator through which I can generate thumbnail images. I found some code and tried to implement that but thumb images look too ugly and stretched in most of the cases. Solution to good looking thumbnail is that we have to maintain aspect ratio of actual image in our thumbnail image otherwise thumbnail will look really bad. Here is the class through which you can easily generate high quality thumbnails.

using System;
using System.Drawing;
using System.Drawing.Imaging;
 
namespace ConsoleApplication1
{
    public class ThumbnailGenerator
    {
        /// <summary>
        /// Generates the thumbnail of given image.
        /// </summary>
        /// <param name="actualImagePath">The actual image path.</param>
        /// <param name="thumbnailPath">The thumbnail path.</param>
        /// <param name="thumbWidth">Width of the thumb.</param>
        /// <param name="thumbHeight">Height of the thumb.</param>
        public static void Generate(string actualImagePath, string thumbnailPath, int thumbWidth, int thumbHeight)
        {
            Image orignalImage = Image.FromFile(actualImagePath);
 
            // Rotating image 360 degrees to discart internal thumbnail image
            orignalImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            orignalImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
 
            // Here is the basic formula to mantain aspect ratio
            // thumbHeight   imageHeight     
            // ----------- = -----------   
            // thumbWidth    imageWidth 
            //
            // Now lets assume that image width is greater and height is less and calculate the new height
            // So as per formula given above
            int newHeight = orignalImage.Height * thumbWidth / orignalImage.Width;
            int newWidth = thumbWidth;
 
            // New height is greater than our thumbHeight so we need to keep height fixed and calculate the width accordingly
            if (newHeight > thumbHeight)
            {
                newWidth = orignalImage.Width * thumbHeight / orignalImage.Height;
                newHeight = thumbHeight;
            }
 
            //Generate a thumbnail image
            Image thumbImage = orignalImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
 
            // Save resized picture
            var qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
            var quality = (long)100; //Image Quality 
            var ratio = new EncoderParameter(qualityEncoder, quality);
            var codecParams = new EncoderParameters(1);
            codecParams.Param[0] = ratio;
            //Right now I am saving JPEG only you can choose other formats as well
            var codecInfo = GetEncoder(ImageFormat.Jpeg);
 
            thumbImage.Save(thumbnailPath, codecInfo, codecParams);
 
            // Dispose unnecessory objects
            orignalImage.Dispose();
            thumbImage.Dispose();
        }
 
        /// <summary>
        /// Gets the encoder for particulat image format.
        /// </summary>
        /// <param name="format">Image format</param>
        /// <returns></returns>
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
    }
}

To use this class simply call Generate function of ThumbnailGenerator class. Here is a sample:-
ThumbnailGenerator.Generate(@"C:\images\myPicture.jpg", @"C:\images\myPictureThumb.jpg", 100, 150);