将数据从用户控件导出到ASP.NET中的Excel工作表

时间:2013-03-28 06:19:22

标签: asp.net user-controls export-to-excel

我有一个包含数据的用户控件,基本上就像问题和答案(有或没有选项)。现在,我想在单击按钮时将用户控件中的整个数据导出到Excel工作表。我怎样才能做到这一点? 任何建议都将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

您必须创建包含table trtd的结构,然后才能将其导出为Excel。
另外,如果您只有datatablecollection类似的来源,那么您可以将其导出为ex​​cel。
您必须写function来将user-control更改为集合,然后才能将其导出为Excel。

以下是示例代码

<table id="mytable" runat="server">
    <tr ><td>1</td></tr>
    <tr><td>2</td></tr>
    </table>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

 protected void Button1_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition","attachment;filename=myexcel.xls");
    Response.ContentType = "application/ms-excel";
    System.IO.StringWriter sw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
    mytable.RenderControl(hw);
    Response.Write(sw.ToString());
    Response.End();

}
public override void VerifyRenderingInServerForm(Control control)
{

}

答案 1 :(得分:0)

这是我用来执行此操作的代码。

public class ExcelUtility
{
    public static void ToExcel(object dataSource)
    {
        GridView grid = new GridView { DataSource = dataSource };
        grid.DataBind();

        StringBuilder sb = new StringBuilder();
        foreach (TableCell cell in grid.HeaderRow.Cells)
            sb.Append(string.Format("\"{0}\",", cell.Text));
        sb.Remove(sb.Length - 1, 1);
        sb.AppendLine();

        foreach (GridViewRow row in grid.Rows)
        {
            foreach (TableCell cell in row.Cells)
                sb.Append(string.Format("\"{0}\",", cell.Text.Trim().Replace("&nbsp;", string.Empty)));
            sb.Remove(sb.Length - 1, 1);
            sb.AppendLine();
        }
        ExportToExcel(sb.ToString());
    }

    private static void ExportToExcel(string data)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Report.csv");
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1255");
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.Write(data);
        HttpContext.Current.Response.End();
    }
}