【问题标题】:Export gridview data to xlsx format?将gridview数据导出为xlsx格式?
【发布时间】:2014-09-29 16:51:43
【问题描述】:

我有一个大的 gridview 作为 Web 应用程序的一部分,它结合了绑定字段和模板字段,并定义了 DataFormatStrings 来定义值在单元格上的表示方式。我很难将所有这些转换为数据表,以便我可以将它们写入 Excel 工作表。

将 gridview 直接转换为 excel 迫使我使用仅生成 .xls 格式的 String Write 和 Html Write。我们正在考虑将所有 excel 下载选项标准化为 .xlsx 格式。这是我到目前为止所尝试的

dt = gvInvoicesEX.DataSource as DataTable;

DataSource 属性由于某种原因返回 null。我还尝试了循环内的正常循环技术来遍历网格视图中的每个单元格并将其复制到数据表中,但我只是得到一个充满空白单元格的数据表。

for (int i = 0; i < gvInvoicesEX.Rows.Count; i++)
{
     DataRow dr = dt.NewRow();
     for (int j = 1; j < gvInvoicesEX.Columns.Count; j++)
     {
          gvInvoicesEX.Rows[i].Cells[j].Attributes.Add("class", "text");
          dr[j - 1] = gvInvoicesEX.Rows[i].Cells[j].Text;   
     }
     dt.Rows.Add(dr);
}

以下是我的excel转换代码:

using (var wb = new XLWorkbook())
{
    DataTable dt = GetDataTableFromGridView();
    string fileName = "BillingDetail" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
    wb.Worksheets.Add(dt);
    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
    using (var ms = new System.IO.MemoryStream())
    {
        wb.SaveAs(ms);
        ms.WriteTo(Response.OutputStream);
        ms.Close();
    }
    Response.End();
}

我可以在上述任何一项中进行更改以使这一切顺利进行吗?

【问题讨论】:

    标签: c# asp.net gridview datatable


    【解决方案1】:

    您应该真正地直接处理来自源的数据,这些数据馈送到您的 gridview 中,而不是尝试处理 gridview 内的数据并将其复制回来。 Gridview 使用反射和许多真正高开销的过程,因此通过直接从数据源进行迭代和格式化,您将跳过很多开销并大大加快您的工作流程。

    因此,使用用于将数据加载到 gridview 中的方法,无论是调用存储过程还是其他方法,您都应该将该数据加载到强类型对象列表中并遍历这些对象以生成您的 Excel 工作表。

    我也强烈建议,除非您在工作表中使用复杂的公式或类似的公式,否则只允许标准化下载为 .csv。 Excel 将很容易地读取该格式,并且它比使用.xlsx 驱动程序更加开放和易于使用。

    【讨论】:

    • 感谢详细的回复。不幸的是,由于用户制定的严格准则,限制为 csv 不是一个可行的选择,而且 gridview 不是我想出的可选步骤。网站的用户可以选择查看数字该网站以及能够以 excel 格式下载。
    • 好的,在这种情况下,为您的 Excel 使用与创建 gridview 相同的数据源,您的生活应该会轻松很多。
    【解决方案2】:

    这是我如何通过单击按钮将我的 gridview 导出为 xslx 格式的。无需再次从数据源中获取。只需像

    一样遍历您的gridview
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (jvGrid.Rows.Count > 0)
            {
                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=Jv entries_" + cboQuater.SelectedValue +" qtr " + cboYear.SelectedValue + ".xlsx");
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    
                StringWriter sw = new StringWriter();
                jvGrid.HeaderRow.Style.Add("background-color", "#fff");
                jvGrid.HeaderRow.Style.Add("color", "#000");
                jvGrid.HeaderRow.Style.Add("font-weight", "bold");
    
                for (int i = 0; i < jvGrid.Rows.Count; i++)
                {
                    GridViewRow grow = jvGrid.Rows[i];
                    grow.BackColor = System.Drawing.Color.White;
                    grow.Attributes.Add("class", "textmode");
                }
    
                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                {
                    jvGrid.RenderControl(hw);
                    Response.Output.Write(sw.ToString());
                    Response.Flush();
                    Response.End();
                }
    
            }
    }
    

    请在您的代码中包含System.IO 命名空间。

    【讨论】:

    • 我尝试了您的方法并收到错误“Excel 无法打开文件,因为文件格式或扩展名无效”。是不是你也遇到过?
    • @Sai Nope。你的机器上安装了excel 2010吗?这在我的机器上运行良好。
    • 不,我只安装了 2007。
    • @Sai 这适用于 Office Standard 2010。也许 Response.ContentType 对于 Office 2007 是不同的。
    【解决方案3】:

    Gridview 导出到 XLSX:-

    我正在使用名为 EPPlus.dll 的库进行导出。只需从链接 http://epplus.codeplex.com/ 下载 EPPlus.dll 并在您的项目中将命名空间称为 using OfficeOpenXml;。

       <asp:GridView ID="grdDisplay" ShowHeaderWhenEmpty="True" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical"
                            OnRowCommand="grdDisplay_RowCommand" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true" DataKeyNames="ID" OnPageIndexChanging="grdDisplay_PageIndexChanging"
                             PageSize="10" OnSorting="Sorting"  >
                            <AlternatingRowStyle BackColor="#DCDCDC" />
                            <FooterStyle BackColor="#DDE8F0" ForeColor="Black" />
                            <HeaderStyle BackColor="#DDE8F0" Font-Bold="True" ForeColor="Black"/>
                            <PagerSettings Mode="NextPrevious" NextPageText="Next" PreviousPageText="Previous" />
                            <PagerStyle BackColor="#DDE8F0" ForeColor="Black" HorizontalAlign="Center" />
                            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                            <SortedAscendingCellStyle BackColor="#F1F1F1" />
                            <SortedAscendingHeaderStyle BackColor="#0000A9" />
                            <SortedDescendingCellStyle BackColor="#CAC9C9" />
                            <SortedDescendingHeaderStyle BackColor="#000065" />
                           <Columns>
                               <asp:TemplateField>
                                   <ItemTemplate>
                                        <asp:ImageButton ID="imgEdit" Width="25px" Height="25px" runat="server"  CommandName="Edit" CommandArgument='<%#Eval("ID")%>' ImageUrl="../Images/edit.png" />
                                   </ItemTemplate>
                               </asp:TemplateField>
                                  <asp:TemplateField>
                                   <ItemTemplate>
                                        <asp:ImageButton ID="imgSearch" Width="25px" Height="25px" runat="server" CommandName="Search" CommandArgument='<%#Eval("ID")%>' ImageUrl="../Images/search.png" />
                                   </ItemTemplate>
                               </asp:TemplateField>
                               <asp:TemplateField>
                                   <ItemTemplate>
                                        <asp:ImageButton ID="imgHistory" Width="25px" Height="25px" runat="server" CommandName="History" CommandArgument='<%#Eval("ID")%>' ImageUrl="../Images/history2.png" />
                                   </ItemTemplate>
                               </asp:TemplateField>
    
                                    <asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-Wrap="false" SortExpression="ID">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                    <asp:BoundField DataField="col2" HeaderText="col2" ItemStyle-Wrap="false" SortExpression="col2">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                    <asp:BoundField DataField="col3" HeaderText="col3" ItemStyle-Wrap="false" SortExpression="col3">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                    <asp:BoundField DataField="col4" HeaderText="col4" ItemStyle-Wrap="false" SortExpression="col4">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                    <asp:BoundField DataField="col5" HeaderText="col5" ItemStyle-Wrap="false" SortExpression="col5">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                    <asp:BoundField DataField="col6" HeaderText="col6" ItemStyle-Wrap="false" SortExpression="col6">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                <asp:BoundField DataField="col7" HeaderText="col7" ItemStyle-Wrap="false" SortExpression="col7">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                <asp:BoundField DataField="col8" HeaderText="col8" ItemStyle-Wrap="false" SortExpression="col8">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                <asp:BoundField DataField="col9" HeaderText="col9" ItemStyle-Wrap="false" SortExpression="col9">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                <asp:BoundField DataField="col10" HeaderText="col10" ItemStyle-Wrap="false" SortExpression="col10">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                <asp:BoundField DataField="col11" HeaderText="col11" ItemStyle-Wrap="false"  SortExpression="col11">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                <asp:BoundField DataField="col12" HeaderText="col12" ItemStyle-Wrap="false"  SortExpression="col12">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                <asp:BoundField DataField="col13" HeaderText="col13" ItemStyle-Wrap="false" SortExpression="col13">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                <asp:BoundField DataField="col14" HeaderText="col14" ItemStyle-Wrap="false" SortExpression="col14">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                <asp:BoundField DataField="col15" HeaderText="col15" ItemStyle-Wrap="false" SortExpression="col15">
                                            <ItemStyle Wrap="False"></ItemStyle>
                                </asp:BoundField>
                                </Columns>
                                  <EmptyDataTemplate>No Records Available..Please refine your search</EmptyDataTemplate>  
                        </asp:GridView>
    

    按钮导出:-

     <asp:Button ID="btnExportToExcel"  Text="Export To Excel"  runat="server" AutoPostBack="true" OnClick="btnExportToExcel_Click"    />
    

    导出代码:-

     protected void btnExportToExcel_Click(object sender, EventArgs e)
            {
                try
                {
                    string mySqlQuery = GenerateQuery();
                    List<Product> myGridData = GetGridData(mySqlQuery);
                    grdDisplay.DataSource = myGridData;
                    grdDisplay.DataBind();
                    ExcelPackage excel = new ExcelPackage();
                    var workSheet = excel.Workbook.Worksheets.Add("Product");
                    var totalCols = grdDisplay.Rows[0].Cells.Count;
                    var totalRows = myGridData.Count;
                    var headerRow = grdDisplay.HeaderRow;
                    ///Ignoring the first three columns, Since first three columns are edit, search and history
                    for (var i = 3; i < totalCols; i++)
                    {
                        workSheet.Cells[1, i].Value = grdDisplay.Columns[i].HeaderText;
                    }
                    for (var j = 1; j <= totalRows; j++)
                    {
                        ///Ignoring the first three columns, Since first three columns are edit, search and history
                        for (var i = 3; i < totalCols; i++)
                        {
                            var product = myGridData.ElementAt(j - 1);
                            string hdrTextVal = product.GetType().GetProperty(grdDisplay.Columns[i].HeaderText).Name;
                            if(hdrTextVal == "col5" || hdrTextVal == "col6")
                            {
                                workSheet.Cells[j + 1, i].Style.Numberformat.Format = "MM/DD/YYYY";
                            }
                            if (hdrTextVal == "col7" || hdrTextVal == "col8")
                            {
                                workSheet.Cells[j + 1, i].Style.Numberformat.Format = "hh:mm";                            
                            }
                            workSheet.Cells[j + 1, i].Value = product.GetType().GetProperty(grdDisplay.Columns[i].HeaderText).GetValue(product, null);
                        }
                    }
                    using (var memoryStream = new MemoryStream())
                    {
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        Response.AddHeader("content-disposition", "attachment;  filename=Product-Export.xlsx");
                        excel.SaveAs(memoryStream);
                        memoryStream.WriteTo(Response.OutputStream);
                        Response.Flush();
                        Response.End();
                    }
                }
                catch (ThreadAbortException exc)
                {                
                }
                catch (Exception ex)
                {
                }            
            }
    

    参考资料:-

    https://www.mikesdotnetting.com/article/278/a-better-way-to-export-gridviews-to-excel
    

    【讨论】:

      猜你喜欢
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      相关资源
      最近更新 更多