【求救!!!】把一个table表保存到execl 中,保存的路径可以选择!!
实现功能 :
[align=center][/align]现在我已经得到了table表的所有数据,并且显示在了页面上1!
现在想通过单击【按钮】把table表导出成execl表格,保存的路径可以
选择!!
------解决方案--------------------后台生成一个临时Excel文件,然后使用Response和Attachment方式把文件直接发到页面上去,此时会出现IE下载提示框,用户可选择保存或直接打开,保存时就可以选择路径了。
------解决方案--------------------通过DataGrid或GridView显示表格内容,再用RenderControl生成Excel.
------解决方案--------------------<asp:Button ID="btnServiceExport" runat="server" Text="导出为Excel" OnClick="Export_2" CommandArgument="select * from .............................." />
<asp:DataGrid ID="dg2" runat="server" AutoGenerateColumns="false" DataKeyField="id" Width="100%">
<Columns>
<asp:TemplateColumn HeaderText="aaa" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# getTypeName((DataBinder.Eval(Container.DataItem, "a")).ToString())%>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="bbb" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# getStatus((DataBinder.Eval(Container.DataItem, "b")).ToString())%>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn HeaderText="ccc" DataField="c" DataFormatString="{0:d}" ItemStyle-HorizontalAlign="Center"></asp:BoundColumn>
<asp:BoundColumn HeaderText="ddd" DataField="d" ItemStyle-HorizontalAlign="Left"></asp:BoundColumn>
<asp:BoundColumn HeaderText="eee" DataField="e" ItemStyle-HorizontalAlign="Left"></asp:BoundColumn>
<asp:BoundColumn HeaderText="fff" DataField="f" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="Right"></asp:BoundColumn>
<asp:BoundColumn HeaderText="ggg" DataField="g" ItemStyle-HorizontalAlign="Left"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
public void Export_2(object sender, EventArgs e)
{
using (SqlConnection conn = DB.getConnection())
{
Button btn = (Button)sender;
string sql = btn.CommandArgument.ToString();
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string file = "Invoice" + DateTime.Now.ToShortDateString();
dg2.DataSource = dr;
dg2.DataBind();
Response.Clear();
Response.Buffer = true;
//使用中文
Response.Charset = "gb2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + file + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
//设置格式为Excel
Response.ContentType = "application/ms-excel";
EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(sw);
dg2.RenderControl(tw);
Response.Write(sw.ToString());
Response.End();
}
}