0

我有一个包含数据的用户控件,基本上就像问题和答案(带有是或否选项)。现在我想通过单击按钮将整个数据从用户控件导出到 Excel 工作表。我怎样才能做到这一点?任何建议将不胜感激。

4

2 回答 2

0

您将必须创建一个包含 的结构table trtd然后您可以将其导出到 Excel。
否则,如果您只有一个datatablecollection类似的来源,那么您可以将其导出到 excel。
您必须写信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)
{

}
于 2013-03-28T06:25:22.787 回答
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();
    }
}
于 2013-03-28T06:34:21.743 回答