仅从页面到C#在Excel上导出网格视图数据

时间:2017-02-06 10:43:31

标签: c# asp.net excel

我正在尝试从页面导出网格视图的数据。但是当我将数据导出到excel文件时,它会导出整个页面。我只想导出网格视图的数据。我已经通过几个链接,但没有发现我自己满意。以下是我的导出代码。

  Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            //To Export all pages
            gvWorkOrder.AllowPaging = false;
            this.LoadData();

            gvWorkOrder.HeaderRow.BackColor = Color.White;
            foreach (TableCell cell in gvWorkOrder.HeaderRow.Cells)
            {
                cell.BackColor = gvWorkOrder.HeaderStyle.BackColor;
            }
            foreach (GridViewRow row in gvWorkOrder.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    if (row.RowIndex % 2 == 0)
                    {
                        cell.BackColor = gvWorkOrder.AlternatingRowStyle.BackColor;
                    }
                    else
                    {
                        cell.BackColor = gvWorkOrder.RowStyle.BackColor;
                    }
                    cell.CssClass = "textmode";
                }
            }

            gvWorkOrder.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }

这是我的aspx页面。                                 

                        <asp:TemplateField ItemStyle-ForeColor="#192d98" HeaderStyle-HorizontalAlign="Right">
                                <ItemTemplate>
                                    <asp:LinkButton runat="server" Text="Print" ID="lnkPrint" CommandName="PrintWorkOrder" CommandArgument='<%#Eval("WorkOrderNo") %>' ></asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField ItemStyle-ForeColor="#192d98" HeaderStyle-HorizontalAlign="Right">
                                <ItemTemplate>
                                    <asp:LinkButton runat="server" Text="تحرير" ID="lnkButton" PostBackUrl='<%# string.Format("~/ServiceManagement/WorkOrderCreation_AR.aspx?WorkOrderID={0}", Eval("WorkOrderNo"))%>'></asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>

                            <asp:BoundField HeaderStyle-HorizontalAlign="Right" ItemStyle-ForeColor="#192d98"
                                DataField="Location" HeaderText="فرع">
                                <ItemStyle ForeColor="#192D98"></ItemStyle>
                            </asp:BoundField>
                            <asp:BoundField HeaderStyle-HorizontalAlign="Right" ItemStyle-ForeColor="#192d98"
                                DataField="VendorID" HeaderText="رقم المورد">
                                <ItemStyle ForeColor="#192D98"></ItemStyle>
                            </asp:BoundField>
                            <asp:BoundField HeaderStyle-HorizontalAlign="Right" ItemStyle-ForeColor="#192d98"
                                DataField="CustomerName" HeaderText="اسم العميل">
                                <ItemStyle ForeColor="#192D98"></ItemStyle>
                            </asp:BoundField>
                            <asp:BoundField HeaderStyle-HorizontalAlign="Right" ItemStyle-ForeColor="#192d98"
                                DataField="CustomerID" HeaderText="رقم العميل">
                                <ItemStyle ForeColor="#192D98"></ItemStyle>
                            </asp:BoundField>
                            <asp:BoundField HeaderStyle-HorizontalAlign="Left" ItemStyle-ForeColor="#192d98"
                                DataField="Status" HeaderText="حالة الأمر">
                                <ItemStyle ForeColor="#192D98"></ItemStyle>
                            </asp:BoundField>
                            <asp:BoundField HeaderStyle-HorizontalAlign="Right" ItemStyle-ForeColor="#192d98"
                                DataField="CreatedOn" DataFormatString="{0:dd/MM/yyyy}" HeaderText="تاريخ الأمر">
                                <ItemStyle ForeColor="#192D98"></ItemStyle>
                            </asp:BoundField>
                            <%--<asp:HyperLinkField HeaderStyle-HorizontalAlign="Right" DataNavigateUrlFields="ORIGNUMB,ORIGTYPE"
                                Target="_new" DataNavigateUrlFormatString="SalesOrderCreationReport_ar.aspx?Id={0}&Soptype={1}"
                                DataTextField="ORIGNUMB" HeaderText="# وثيقة الاساسي" />--%>
                            <asp:BoundField HeaderStyle-HorizontalAlign="Right" ItemStyle-ForeColor="#192d98"
                                DataField="WorkOrderNo" HeaderText="رقم أمر الصيانة">
                                <ItemStyle ForeColor="#192D98"></ItemStyle>
                            </asp:BoundField>
                        </Columns>
                        <AlternatingRowStyle BackColor="White" />
                        <EditRowStyle BackColor="#2461BF" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#EFF3FB" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#F5F7FB" />
                        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                        <SortedDescendingCellStyle BackColor="#E9EBEF" />
                        <SortedDescendingHeaderStyle BackColor="#4870BE" />
                    </asp:GridView>

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

安装软件包 ExcelLibrary.SpreadShee t 并创建如下方法。 您需要根据要导出到Excel工作表的记录创建数据表。

    public string Export(DataTable dt)
    {
        Workbook workbook = new Workbook();
        Worksheet sheet = new Worksheet(WorkSheetName);
        workbook.Worksheets.Add(sheet);

        // Adding Columns in Sheet
        int c = 0, r = 0;
        foreach (DataColumn column in dt.Columns)
        {
            sheet.Cells[r, c] = new Cell(column.ColumnName);
            c++;
        }

        // Adding Records into sheet
        r = 1;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (c = 0; c < dt.Columns.Count; c++)
            {
                object o = dt.Rows[i][c];
                int ii;
                if (o == DBNull.Value)
                    sheet.Cells[r, c] = new Cell("");
                else if (int.TryParse(o.ToString(), out ii))
                    sheet.Cells[r, c] = new Cell(ii);
                else
                    sheet.Cells[r, c] = new Cell(o);
            }
            r++;
        }

        // Append Extra rows to comfort Open excel > 2003
        if (dt.Rows.Count < MinRow)
        {
            r++;
            for (int i = 0; i < MinRow; i++)
            {
                for (c = 0; c < 50; c++)
                {
                    sheet.Cells[r, c] = new Cell("");
                }
                r++;
            }
        }

        string fileName = Guid.NewGuid().ToString("N") + ".xls";

        if (!Directory.Exists(DestinationRootFolder))
        {
            Directory.CreateDirectory(DestinationRootFolder);
        }

        workbook.Save(fileName);

        return fileName;
    }

此函数将返回创建的excel文件的路径。你可以用它来回复写下载开始。

    HttpResponse httpResponse = Response;
    httpResponse.Clear();
    HttpContext.Current.Response.ContentType = "application/ms-excel";
    httpResponse.AddHeader("content-disposition", "attachment;filename=" + tName);
    using (MemoryStream memoryStream = new MemoryStream())
    {
        try
        {
            using (FileStream fileStream = new FileStream(fName, FileMode.Open))
            {
                fileStream.CopyTo(memoryStream);
            }
            memoryStream.WriteTo(httpResponse.OutputStream);
        }
        finally
        {
            memoryStream.Close();
            File.Delete(fName);
        }
    }

    httpResponse.End();

注意:您需要在目录中写入权限才能编写此excel文件。

答案 1 :(得分:0)

我有一个将GridView数据导出(或转换)为Excel文件的示例。

我使用iTextSharp使它工作。这是我的代码:Exporting GridView to Excel