Download grid view and some text into a excel in asp.net website
I am binding data to a grid view.
string MysqlStatement = "SELECT TimeReceived,TimeRead, Concat(FirstName,', ',LastName) as Name FROM tbl_usermessage INNER JOIN tbl_user on tbl_usermessage.UserID = tbl_user.UserID WHERE MsgID = @Value1";
using (DataServer server = new DataServer())
{
MySqlParameter[] param = new MySqlParameter[1];
param[0] = new MySqlParameter("@value1", MySqlDbType.Int32);
param[0].Value = MessageID;
command.Parameters.AddWithValue("@Value1", MessageID);
ds = server.ExecuteQuery(CommandTy开发者_开发知识库pe.Text, MysqlStatement, param);
}
Grid_UserTable.DataSource = ds;
Grid_UserTable.DataBind();
I am binding data to a repeater list,
string MysqlStatement = "SELECT Title, RespondBy, ExpiresBy, OwnerName, Concat(LowTarget,' - ',TopTarget) as Threshold FROM tbl_message WHERE MsgID = @Value1";
using (DataServer server = new DataServer())
{
MySqlParameter[] param = new MySqlParameter[1];
param[0] = new MySqlParameter("@value1", MySqlDbType.Int32);
param[0].Value = MessageID;
command.Parameters.AddWithValue("@Value1", MessageID);
ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, param);
}
rptList.DataSource = ds;
rptList.DataBind();
I have a button to download the report
protected void btn_ExcelDownload_Click(object sender, EventArgs e)
{
string path = Server.MapPath("");
path = path + @"\Resources\MessageStatus.xlsx";
string filename = Path.GetFileName(path);
Response.AppendHeader("content-disposition", "attachment; filename=" + filename);
Response.ContentType = "Application/msexcel";
Response.WriteFile(path);
Response.End();
}
I tried few things and managed to download the excel sheet from the button click, but How can I fill all the data from the repeater list and grid view. I haven't done this before pls help.
Sample aspx:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>Whatever <%# Container.DataItem %></td>
<td>Stuff <%# Container.DataItem %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Sample code behind
protected void Button1_Click(object sender, EventArgs e) {
Repeater1.DataSource = Enumerable.Range(1, 10);
Repeater1.DataBind();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);
Repeater1.RenderControl(writer);
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=foo.xlsx");
Response.ContentType = "Application/msexcel";
Response.Write(sb.ToString());
Response.End();
}
精彩评论