0

基本的に質問と回答のようなデータを含むユーザーコントロールがあります(はいまたはいいえのオプション付き)。ボタンをクリックすると、ユーザーコントロールからExcelシートにデータ全体をエクスポートしたいと思います。どうすればこれを達成できますか?どんな提案でも大歓迎です。

4

2 に答える 2

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(" ", 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 に答える
0

を含む構造を作成する必要がtable trありtd、それを Excel にエクスポートできます。
それ以外の場合は、datatableまたはcollection同様のソースがある場合にのみ、それを Excel にエクスポートできます。コレクションを変更する
には、書き込む必要があります。その後、それを Excel にエクスポートできます。functionuser-control

これがサンプルコードです

<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 に答える