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.

Comments (38)

Loading... Logging you in...
  • Logged in as
This is a wonderful tutorial
2 replies · active 538 weeks ago
Good article
1 reply · active 675 weeks ago
Thanks. Very useful.
1 reply · active 675 weeks ago
I get this error at ws.Cells.Style.Font.Size = 11;

Error1'OfficeOpenXml.ExcelWorksheet' does not contain a definition for 'Cells' and no extension method 'Cells' accepting a first argument of type 'OfficeOpenXml.ExcelWorksheet' could be found (are you missing a using directive or an assembly reference?)C:ProjectsConsoleExcel2007XLClasses.cs1616ConsoleExcel2007
1 reply · active 675 weeks ago
Hi . I would like to know if its possible to have two different fonts with two different colours within the same cell using this plugin. If it can be done also please outline how to achieve the same...

Thanks in advance..
1 reply · active 623 weeks ago
what dll i should be added to export the excel sheet
1 reply · active 623 weeks ago
Hi,
i want to write 90000X50 rows to a excel before i download. writing cell by cell will be very slow. is there anyway we can write a 2d array to excel directly? that will help because, i will form the 2d array seperatly and write to excel in one shot instead of writing cell by cell. this will enhance the performance.
kindly suggest.
Thanks.
1 reply · active 623 weeks ago
i tried using a dataset. it throws out of memory exception. so guessing datatable wll also throw the same exception. is it not so?
1 reply · active 575 weeks ago
Hi,

I used epplus to export my datatable as excel in C#.net.The problem here is i want to do Indent for some paticular cell.So,I have used
var indent = cell.Style.Indent;
indent = 10;
(have given values from 10 to 100 and more..).But,it is not working.Pls help
Syed Hashmi's avatar

Syed Hashmi · 622 weeks ago

I am running in to a problem with ExcelPackage library. See my code below.

Dim FI As New System.IO.FileInfo(OpenFileDialog1.FileName)
Dim XP As New ExcelPackage(FI)
Dim WS As ExcelWorksheet = XP.Workbook.Worksheets("Sheet1")

' SET VALUES
WS.Cell(6, 6).Value = "6"
WS.Cell(6, 7).Value = "7"
WS.Cell(6, 8).Formula = "SUM(F6:G7)"

But I don’t get the total of the above cells with following statement:
txtResult.Text = WS.Cell(6, 8).Value

I was expecting a total of SUM as per formuls.
Can you help.
1 reply · active 575 weeks ago
Nocturns2's avatar

Nocturns2 · 593 weeks ago

@Zeeshan I've seen many pages that show how to create and manipulate excel documents using ep plus. What would like to see is a code sample that shows how to read an excel file (that someone uploads to my server) using ep plus.
Can you please let me know the how can i create multiplesheets in one Excel File............
1 reply · active 575 weeks ago
can we add multiple sheet ?
1 reply · active 564 weeks ago
Thank you for this articl, i want juste know how can i use EPPlus in my class c# cobehind i can't make that using EPPlus;
1 reply · active 561 weeks ago
How to change row Heigth ?
3 replies · active 530 weeks ago
Thank you for the best quick start guide I have ever seen. Really quick and helpful!
1 reply · active 530 weeks ago
ok I got a problem. The first excel sheet works fine. It then creates the tabs for the next two sheets ok. Some reason the data is not populating on the other two tabs. I can loop through the create data add see the values. I know my data tables are populating. Any idea why the other two tabs are blank?
1 reply · active 530 weeks ago
hi,
how i will export two different table format in same excel sheet.
I found one more Blog about Microsoft Excel which is very helpful in learning Advance Excel.
Nice to read this article... Thanks for sharing....

Post a new comment

Comments by