Reputation: 1123
I am very new to asp.net development
I have presented the user to download the asp repeater grid details
in excel format on button click. I have done it with following code which I got after googling
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ExcelExport.xls");
for (int i = 0; i < RptMasterData.Items.Count; i++)
{
Table tbl = (Table)RptMasterData.Items[i].FindControl("tblTest");
tbl.Style.Add("background-color", "#FF9900");
GridView gvAllocation = (GridView)RptMasterData.Items[i].FindControl("gvAllocation");
gvAllocation.HeaderRow.Style.Add("background-color", "#95c556");
int j = 1;
foreach (GridViewRow gvrow in gvAllocation.Rows)
{
gvAllocation.BackColor = System.Drawing.Color.White;
if (j <= gvAllocation.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
}
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
RptMasterData.RenderControl(hw);
Response.Write("<table>");
Response.Output.Write(sw.ToString());
Response.Write("<table>");
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Close();
The file is downloaded as excel file.But when I try to open the file in MS office I get the Error message as
The problem occurred when I try to edit and save the file in Ms-office. then it shows following warning
So I Just tried to open the same in text editor and found that the file downloaded is an HTML file containing the needed data as expected not excel file.
Can anyone guide me in how to create an actual Excel file for downloading when user click "Download"
Upvotes: 0
Views: 1051
Reputation: 397
Codeplex EPPlus http://epplus.codeplex.com/ is Good liberary to create Spreadsheet document in the server
Upvotes: 2