2

需要帮助将我的 gridview 转换为 excel 文档。我已经尝试了几个示例,但似乎无法正确处理。任何帮助将非常感激。这是我的 gridview 代码,它是从 SQL 数据库中填充的。

<div>
    <asp:GridView Align="Center" ID="gvResults" AutoGenerateColumns="false" runat="server" Width="608px"
        Style="width: 80%; margin-bottom: 0px" CellPadding="4" ForeColor="#333333" GridLines="None"
        OnRowDataBound="gvResults_RowDataBound">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Image ID="imgDataMoreInfo" ImageUrl="T:\Groups\IntResoures\pic\tabpic.jpg" CssClass="img_data_moreinfo" Height="7" Width="7" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Government Name & Address">
                <ItemTemplate>
                    <asp:Label ID="lblGovernmentNameAddress" runat="server" Text=""></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="DOB" HeaderText="DOB" />
            <asp:TemplateField HeaderText="SSFHS Name & Address">
                <ItemTemplate>
                    <asp:Label ID="lblSSFHSNameAddress" runat="server" Text=""></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="ssfhsdob" HeaderText="DOB" />
            <asp:TemplateField HeaderText="Match Status">
                <ItemTemplate>
                    <asp:RadioButtonList ID="rblMatchStatus" runat="server" RepeatDirection="Vertical"></asp:RadioButtonList>
                    <asp:Label ID="lblFirst" CssClass="displayNone" runat="server" />
                    <asp:Label ID="lblSecond" CssClass="displayNone" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EditRowStyle BackColor="#999999" />
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#506C8C" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>
</div>

我的导出按钮和事件

<asp:Button ID="btnExportToExcel" OnClick="btnExportToExcel_Click" runat="server" Text="Export to Excel" Width="89px" Font-Size="X-Small" />




 protected void btnExportToExcel_Click(object sender, EventArgs e)
{

}
4

3 回答 3

2

这是与您的代码相关的更具体的一个:

 protected void btnExportToExcel_Click(object sender, EventArgs e)
{
    Response.Clear();

    Response.AddHeader("content-disposition", "attachment;
    filename=FileName.xls");

    Response.Charset = "";

    // If you want the option to open the Excel file without saving than

    // comment out the line below

    // Response.Cache.SetCacheability(HttpCacheability.NoCache);

    Response.ContentType = "application/vnd.xls";

    System.IO.StringWriter stringWrite = new System.IO.StringWriter();

    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    gvResults.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());

    Response.End();

}

于 2013-06-11T15:47:40.367 回答
1

我上周刚做了这个。

这是您需要放置在您的 aspx 文件中的代码(您可以根据自己的喜好调整高度和宽度):

<asp:Button ID="ButtonA" runat="server" height="20px" OnClick="ButtonA_Click" Text="Export me" Width="200px />

在您的 aspx 页面顶部的页面部分插入:

EnableEventValidation="false"

在您的 cs 文件中,将以下内容放在“受保护的 void Page_Load...”部分下方:

Protected void ButtonA_Click(object sender, EventArgs e)
{
     Response.Clear();
     Response.AddHeader("content-disposition", "attachment;filename=Filename.xls");
     Response.ContentType = "application/vnd.xlsx";
     System.IO.StringWriter stringWrite = new System.IO.StringWriter();
     System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
     GridView1.RenderControl(htmlWrite);
     Response.Write(stringWrite.ToString());
     Response.End();
}

忽略出现的错误并单击“是”。出现错误是因为生成的文件不是纯 Excel 文件类型。它生成一个本质上是文本的文件。将其保存为电子表格,您就可以开始使用了。

于 2013-06-12T02:44:03.783 回答
0

通常在写入excel时

GridView1.RenderControl(htmlWrite);
 Response.Write(stringWrite.ToString());

将简单地将其保存为 html 表到 excel而不是二进制文件。检查,好像你很担心。

我的项目中也有同样的问题。

那么

  • 我只是在我的项目文件夹中创建空的 xcel 文件模板,
  • 然后我向它写入数据。

    string filePath = Server.MapPath("~/ReportFiles/CenterMemberAddressDifferentReport_" + Emp_Session._UserMasterId + ".xls");
        System.IO.File.Copy(Server.MapPath("~/Images/ExcelTemplate.xls"), filePath, true);
    
            System.Threading.Thread.Sleep(1000);
    
            string driver = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filePath + "';Extended Properties=Excel 8.0;";
            System.Data.OleDb.OleDbConnection Con = new System.Data.OleDb.OleDbConnection(driver);
            System.Data.OleDb.OleDbCommand Com = Con.CreateCommand();
            System.Data.OleDb.OleDbDataAdapter reader = new OleDbDataAdapter();
            Con.Open();
            DataTable dtSheet = Con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string SQL = "";
    
            foreach (DataRow Row in dt1.Rows)
            {
                string values = "";
                for (int ik = 0; ik < dt1.Columns.Count; ik++)
                {
                    if (values != "") values += ",";
                    values += "'" + Row[ik].ToString() + "'";
                }
                SQL = "INSERT INTO [Sheet1$] ([CENTER NAME],[CENTER ADDRESS],[MEMBER ID],[MEMBER NAME],[MEMBER ADDRESS],[MEMBER COUNT]) VALUES(" + values + ")";
                Com.CommandText = SQL;
                Com.ExecuteNonQuery();
            }
            Con.Close();
    
            System.Threading.Thread.Sleep(1000);
    
            System.IO.FileStream stream = System.IO.File.OpenRead(filePath);
            byte[] by = new byte[stream.Length];
            stream.Read(by, 0, by.Length);
            stream.Close();
            System.Threading.Thread.Sleep(1000);
            System.IO.File.Delete(filePath);
    
            Response.OutputStream.Write(by, 0, by.Length);
            Response.End();
    

基本上我是在将相同的 excel 导入另一个数据源的情况下,并且是 seccesfull。


希望它也能帮助你。请要求提供反馈。谢谢你的美丽问题。

于 2013-07-08T06:56:05.007 回答