Showing posts with label Excel. Show all posts
Showing posts with label Excel. Show all posts

Monday, April 15, 2013

How to Export a Data Table to Excel - Asp.Net, XML

Introduction :

Many times we need to save or export data table to excel spreadsheet on server. Here I will explain how to export data from a data table to Excel using ASP.Net & XML. Here is the following code below:-

data table to excel, c# excel,aspnet,download excel, save as to excel,Export DataTable to Excel in Asp.Net without using excel interop,exporting to Excel using Open XML,c#,save as, download,excel


Default.cs Code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    const int rowLimit = 65000;

Export Gridview to Excel - Asp.Net

Introduction :

In this article I will explain how to export from a GridView data to an Excel file. In the following example we will use RenderControl method outputs server control content (to a provided HtmlTextWriter object and stores tracing information) about the control if tracing is enabled.

This method will confirms that an HtmlForm control is rendered for the specified Asp.Net server control at run time.

c# excel,gridview export,excel spreadsheet,export data from excel,excel documents,aspnet,simple example


Default.cs Code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;


public partial class _Default : System.Web.UI.Page
{
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        dt.Columns.Add("EmpId", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        dt.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //
        dt.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
        dt.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
        dt.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
        dt.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
        dt.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void btnexport_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=gridviewdata.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sWriter = new StringWriter();
            HtmlTextWriter hWriter = new HtmlTextWriter(sWriter);
            GridView1.RenderControl(hWriter);
            Response.Output.Write(sWriter.ToString());
            Response.Flush();
            Response.End();
        }
        catch (Exception ex)
        {
            Label1.Text = ex.ToString();
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
    }
}
  •  To download example source code click here

Saturday, December 29, 2012

How to export dataset to excel in C#?

Introduction:

Many times we need to export reports in excel format. So here I will explain how to export Dataset or Datatable in Excel file. Follow the below instructions:

1. Add reference to Microsoft.Office.Interop.Excel.dll

2. using System.Runtime.InteropServices;

Source:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <br />
       
        <asp:Button ID="btnExportExcel" runat="server" Text="Export To Excel"
            onclick="btnExportExcel_Click" />
    </div>
    </form>
</body>
</html>




Code Behind:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Runtime.InteropServices;

public partial class _Default : System.Web.UI.Page
{
    DataTable productsDataTable = new DataTable();
  
    protected void Page_Load(object sender, EventArgs e)
    {
        // create DataTable object   

        // auto increment column for productsDataTable
        DataColumn dataColumn = new DataColumn("AutoID", System.Type.GetType("System.Int32"));
        dataColumn.AutoIncrement = true;
        dataColumn.AutoIncrementSeed = 1;
        dataColumn.AutoIncrementStep = 1;
        dataColumn.Unique = true;
        productsDataTable.Columns.Add(dataColumn);

        // product id column
        dataColumn = new DataColumn("ProductID", System.Type.GetType("System.Int32"));
        productsDataTable.Columns.Add(dataColumn);

        // product name column
        dataColumn = new DataColumn("ProductName", System.Type.GetType("System.String"));
        productsDataTable.Columns.Add(dataColumn);

        // quantity column
        dataColumn = new DataColumn("ProductQuantity", System.Type.GetType("System.Int32"));
        productsDataTable.Columns.Add(dataColumn);

        // product price column
        dataColumn = new DataColumn("ProductPrice", System.Type.GetType("System.Decimal"));
        productsDataTable.Columns.Add(dataColumn);


        // After Creating columns you can add data rows to store the data dynamically

        DataRow dataRow = productsDataTable.NewRow();
        dataRow["ProductID"] = 43;
        dataRow["ProductName"] = "Ipoh Coffee";
        dataRow["ProductQuantity"] = 1;
        dataRow["ProductPrice"] = 46.00;
        productsDataTable.Rows.Add(dataRow);

        dataRow = productsDataTable.NewRow();
        dataRow["ProductID"] = 40;
        dataRow["ProductName"] = "Boston Crab Meat";
        dataRow["ProductQuantity"] = 1;
        dataRow["ProductPrice"] = 18.40;
        productsDataTable.Rows.Add(dataRow);

        GridView1.DataSource = productsDataTable;
        GridView1.DataBind();
    }
    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(productsDataTable);
            ExportToExcel(ds, "test");
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    // Function to export dataset to excel file
    public void ExportToExcel(DataSet dataset, string DestFileName)
    {
        try
        {
            if (System.IO.File.Exists(DestFileName))
            {
                System.IO.File.Delete(DestFileName);
            }
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook excelWorkBook = default(Microsoft.Office.Interop.Excel.Workbook);
            excelWorkBook = excelApp.Workbooks.Add(Type.Missing);
            int sheetIndex = 0;
            int col = 0;
            int row = 0;
            Microsoft.Office.Interop.Excel.Worksheet excelSheet = default(Microsoft.Office.Interop.Excel.Worksheet);
            foreach (System.Data.DataTable dt1 in dataset.Tables)
            {
                sheetIndex += 1;
                object[,] rawData = new object[dt1.Rows.Count + 1, dt1.Columns.Count];
                for (col = 0; col <= dt1.Columns.Count - 1; col++)
                {
                    rawData[0, col] = dt1.Columns[col].ColumnName;
                }
                for (col = 0; col <= dt1.Columns.Count - 1; col++)
                {
                    for (row = 0; row <= dt1.Rows.Count - 1; row++)
                    {
                        rawData[row + 1, col] = dt1.Rows[row].ItemArray[col];
                    }
                }
                string finalColLetter = string.Empty;
                string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                int colCharsetLen = colCharset.Length;
                if (dt1.Columns.Count > colCharsetLen)
                {
                    finalColLetter = colCharset.Substring((dt1.Columns.Count - 1) / colCharsetLen - 1, 1);
                }
                finalColLetter += colCharset.Substring((dt1.Columns.Count - 1) % colCharsetLen, 1);
                excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkBook.Worksheets.get_Item(sheetIndex);
                excelSheet.Name = dt1.TableName;
                string excelRange = string.Format("A1:{0}{1}", finalColLetter, dt1.Rows.Count + 1);
                excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;

                //int colcount = excelSheet.Cells.CurrentRegion.Columns.Count;
                string excelRange1 = string.Format("A1:{0}{1}", finalColLetter, 1);
                excelSheet.get_Range(excelRange1, Type.Missing).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue);
                excelSheet.get_Range(excelRange1, Type.Missing).Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                excelSheet.get_Range(excelRange1, Type.Missing).Font.Bold = true;
                excelSheet = null;
            }
            string e = System.IO.Path.GetExtension(DestFileName);
            if (e == ".csv")
            {
                excelWorkBook.SaveAs(DestFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVMSDOS, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing);
            }
            else if (e == ".xls")
            {
                excelWorkBook.SaveAs(DestFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing);
            }

            //use this commented code for auto save file
            //else if (e == "")
            //{
            //    excelWorkBook.SaveAs(DestFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing,
            //    Type.Missing, Type.Missing);
            //}

            GC.Collect();
            GC.WaitForPendingFinalizers();
            excelWorkBook.Close(trueType.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(excelWorkBook);
            excelApp.Quit();
            Marshal.FinalReleaseComObject(excelApp);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
   
}

To download the sample code click here. I hope this will help you out.