Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have some tables in my Sql server 2007 database I need to copy the contents of the table into an excel sheet by selecting the table name in a dropdownlist.with an event or method through the front end in the asp.net using C# code.plz help me.....
Posted

Refer to the following link. this could be useful to achieve what you want.

Export to EXCEL from Datatable in C#.Net[^]
 
Share this answer
 
Comments
srinath.pothineni 22-Aug-12 7:31am    
thankq rahul its useful for me and i got the solution....
Rahul Rajat Singh 22-Aug-12 7:33am    
good to hear that. if it is working mark them as solutions so that other will know it is solved and perhaps someone else can also benefit from it.
srinath.pothineni 22-Aug-12 7:32am    
one more question rahul i want to generate log files when i create an excel file how can i do this...
Rahul Rajat Singh 22-Aug-12 7:34am    
Where do you want to write logs, text file or eventlog?
srinath.pothineni 22-Aug-12 7:43am    
sorry for the delay...
i want to write in .txt file...
I hope you get the answer here Export GridView Data to Excel using OpenXml[^]
 
Share this answer
 
Comments
srinath.pothineni 22-Aug-12 2:34am    
Thanks Pramod.I want to convert the table data to excel sheet directly with out a gridview.plz send me the exact code...
ythisbug 22-Aug-12 2:41am    
@Srinath
simple idea is add column to perticular table and save field as columnTablename in that field add ur table name.and bind to dropdown as columntable name field and click export then u can get details..try this solution to export to excel.
pramod.hegde 22-Aug-12 2:45am    
You can use this.

string excelfile = Path.GetTempPath() +
Guid.NewGuid().ToString() + ".xlsx";
using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Create(
excelfile,
DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
CreateExcelParts(excelDoc, table);
}
return excelfile;

and 'table' should be of type DataTable. so, all you need to do is, create DataTable from sql and pass it to this method.
Well, try this. Here is the full source to export datatable to excel

public void ExportToExcel(DataTable data, string fileName)
{
    HttpContext context = HttpContext.Current;
    context.Response.Clear();

    context.Response.ContentType = "text/csv";
    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");

    //iterate column header names
    for (int i = 0; i < data.Columns.Count; i++)
    {
        if (i > 0)
        {
            context.Response.Write(",");
        }
        context.Response.Write(data.Columns[i].ColumnName);
    }
    context.Response.Write(Environment.NewLine);

    //prepare data
    foreach (DataRow row in data.Rows)
    {

        for (int i = 0; i < data.Columns.Count; i++)
        {
            if (i > 0)
            {
                context.Response.Write(",");
            }
            context.Response.Write(row.ItemArray[i].ToString());
        }
        context.Response.Write(Environment.NewLine);
    }
    context.Response.End();
}

private DataTable getData()
{
    //return datatable - that you get from database
}

protected void Button1_Click(object sender, EventArgs e)
{
    ExportToExcel(getData(), "[customefilename]");
}


Hope this helps.
cheers
 
Share this answer
 
Check my article. I have explained how to export datatable to excel with formatting. you have to load datatable from database using procedure/query through c#

Export DataTable to Excel with Formatting in C#[^]
 
Share this answer
 
Thanks one and all for your great support.finally i completed the task.its working but it generates .aspx file format it is opening by selecting open with excel option.see the below code and tell me how to generate direct excel file..



Quote:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;

public partial class DbtoExcel : System.Web.UI.Page
{
SqlConnection cn;
DataGrid dg = null;
static SqlCommand cmd;
SqlDataAdapter da = null;
string cs,excelfile;
SqlDataReader dr;
DataSet ds=null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
cs = WebConfigurationManager.ConnectionStrings["Mydbcon"].ConnectionString;
cn = new SqlConnection(cs);
cn.Open();
cmd = new SqlCommand("select table_name from INFORMATION_SCHEMA.Tables", cn);
dr = cmd.ExecuteReader();
ds = new DataSet();
while (dr.Read())
{
ddtable.Items.Add(dr[0].ToString());
}
dr.Dispose();
cn.Close();
}
catch(Exception ex)
{
lerror.Text = ex.Message;
}
}

}

protected void ddtable_SelectedIndexChanged(object sender, EventArgs e)
{
lerror.Text = ddtable.SelectedItem.Text;

}

protected void bdownload_Click(object sender, EventArgs e)
{
da=new SqlDataAdapter("select * from (" + ddtable.SelectedItem.Text + ")", cn);
da.Fill(ds,"tab");
dg = new DataGrid();
dg.DataSource = ds;
dg.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType="application/vnd.ms_excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sqlstringwriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter sqlhtmltextwriter = new System.Web.UI.HtmlTextWriter(sqlstringwriter);
dg.RenderControl(sqlhtmltextwriter);
Response.Write(sqlstringwriter.ToString());
Response.End();
}
 
Share this answer
 
Check Out here PDF WORD AND Excel you Can Download . How to convert GridView data to Excel, PDF, Word file using C#[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900