将gridview数据导出为xlsx格式?

时间:2014-08-06 16:42:22

标签: c# asp.net gridview datatable

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

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

dt = gvInvoicesEX.DataSource as DataTable;

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

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();
}

为了使这一切顺利进行,有什么我可以改变的吗?

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

Gridview导出到XLSX: -

我使用名为EPPlus.dll的库进行导出。只需从链接http://epplus.codeplex.com/下载EPPlus.dll,并在项目中将名称空间称为banana.animate().alpha(1).setDuration(6000) .setInterpolator(new AutoReverseInterpolatorDecorator());

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)
            {
            }            
        }

答案 2 :(得分:0)

这是我在单击按钮时将其导出为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命名空间。