| Author: paresh 30 Aug 2008 | Member Level: Silver | Rating: Points: 6 |
hi
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.Xml; using System.Xml.Xsl;
WorkbookEngine.CreateWorkbook(TableId, Response);
public static void CreateWorkbook(System.Web.UI.HtmlControls.HtmlTable ds, HttpResponse Response)
{
string attachment = "attachment; filename=File1.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/vnd.xls"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); HtmlForm frm = new HtmlForm(); ds.Parent.Controls.Add(frm); frm.Attributes["runat"] = "server"; frm.Controls.Add(ds); frm.RenderControl(htw); Response.Write(sw.ToString()); Response.End();
}
|
| Author: Karthikeyan S 30 Aug 2008 | Member Level: Gold | Rating: Points: 6 |
Hi,
Following is the code to convert datatable value to excel sheet which exists:
Take care of 1. getting proper datatable. 2. creating an excel sheet at the path where your .aspx page is locating or have a file in your desired path and take care of opening an already opened files etc,.
Following is the code for this:
protected void btnCSV_Click(object sender, EventArgs e) { string lstrContent = string.Empty; DataTable ldtContent = YourDataTable; lstrContent += "\n"; lstrContent += "TempJointKRAId\tQuarterCode\tInitiatedTeamHeadId\tGoalType"; // //column heading is hard coded. \t is used to display text in next //cells and \n is used to display text in new line. lstrContent += "\n"; foreach (DataRow ldr in ldtContent.Rows) { lstrContent += ldr["TempJointKRAId"] + "\t" + ldr["QuarterCode"] + "\t" + ldr["InitiatedTeamHeadId"] + "\t" + ldr["GoalType"]; lstrContent += "\n"; }
System.IO.StreamWriter sw = new System.IO.StreamWriter( Server.MapPath("test.xls"),true); sw.Write(lstrContent); sw.Dispose(); }
|
| Author: Rajesh(March-2008 Winner) 30 Aug 2008 | Member Level: Gold | Rating: Points: 6 |
Here's the code:
protected void Page_Load(object sender, EventArgs e) { SqlConnection cn = new SqlConnection("yourconnectionstring"); cn.Open(); SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Users", cn); DataTable dt = new DataTable(); da.Fill(dt); cn.Close(); Response.Clear(); Response.ContentType = "application/vnd.ms-excel"; string sep = ""; foreach (DataColumn dc in dt.Columns) { Response.Write(sep + dc.ColumnName); sep = "\t"; } Response.Write("\n"); int i; foreach (DataRow dr in dt.Rows) { sep = ""; for (i = 0; i < dt.Columns.Count; i++) { Response.Write(sep + dr[i].ToString()); sep = "\t"; } Response.Write("\n"); } }
|