如何删除asp.net excel导出

时间:2018-02-06 22:33:01

标签: c# asp.net excel gridview

在asp.net中,Gridview有一个空单元格,所以当我将它导出到excel时,我会在那个空单元格中获取。 我想用空格替换它。 我该怎么做?

这是我的GridView:

<asp:GridView Width="800px" ID="MyGridView" DataSourceID="DataSource1" AutoGenerateColumns="False"
        runat="Server"  BorderColor="#555555" HorizontalAlign="Center" OnRowDataBound="MyGridView_RowDataBound"
        Font-Names="Verdana" Font-Size="12px" AllowSorting="True" 
        EmptyDataRowStyle-Font-Bold="true" EmptyDataRowStyle-ForeColor="#CC0000">
                <EmptyDataTemplate>*** No data available ***</EmptyDataTemplate>

        <Columns>
            <asp:BoundField HeaderText="COLLEGE" DataField="COLLEGE" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF"
                ReadOnly="true" DataFormatString="{0:N0}"/>
            <asp:BoundField HeaderText="COLLEGE NAME" DataField="COLLEGE DESC" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF"
                ReadOnly="true" DataFormatString="{0:N0}"/>
             <asp:BoundField HeaderText="UNDERGRAD" DataField="UNDERGRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
                HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>    
            <asp:BoundField HeaderText="GRAD" DataField="GRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
                HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
            <asp:BoundField HeaderText="LAW" DataField="LAW" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
                HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>

            <asp:BoundField HeaderText="TOTAL" DataField="TOTAL" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
                HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
        </Columns>
    </asp:GridView> 

这是我的excel导出:

public void ExpToExcel_Click(object sender, EventArgs e)
{     
    MyGridView.DataBind();
    MyGridView.AllowPaging = false;
    MyGridView.ShowHeader = true;
    DataTable dt = new DataTable("GridView_Data");
    foreach (TableCell cell in MyGridView.HeaderRow.Cells)
    {
        dt.Columns.Add(cell.Text);

    }

    int cellcount = MyGridView.Rows[0].Cells.Count;
    foreach (GridViewRow row in MyGridView.Rows)
    {
        DataRow datarw;
        datarw = dt.NewRow();
        for (int i = 0; i < cellcount; i++)
        {
            datarw[i] = row.Cells[i].Text;

        }


        dt.Rows.Add(datarw);
    }
    ExcelPackage excel = new ExcelPackage();

    var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
    workSheet.Cells["J1"].Value = "TEXAS TECH UNIVERSITY";
    workSheet.Cells["J1"].Style.Font.Size = 24;
    workSheet.Cells["J1"].Style.Font.Bold = true;

    workSheet.Cells["I2"].Value = "DEPARTMENT OF INSTITUTIONAL RESEARCH";
    workSheet.Cells["I2"].Style.Font.Size = 20;
    workSheet.Cells["I2"].Style.Font.Bold = true;

    workSheet.Cells["J3"].Value = caption.Text.ToUpper();
    workSheet.Cells["J3"].Style.Font.Bold = true;


    workSheet.Cells["L4"].Value = "(UnCertified Data)";

    workSheet.Cells["A7:F7"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
    workSheet.Cells["A7:F7"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
    workSheet.Cells["A7:F7"].Style.Font.Color.SetColor(System.Drawing.Color.White);

    workSheet.Cells["A21:F21"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
    workSheet.Cells["A21:F21"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
    workSheet.Cells["A21:F21"].Style.Font.Color.SetColor(System.Drawing.Color.White);

    workSheet.Cells[7, 1].LoadFromDataTable(dt, true);


    workSheet.Cells["A7:F7"].AutoFitColumns();

    using (var memoryStream = new MemoryStream())
    {
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=Enrollment_Major_Classification.xlsx");
        excel.SaveAs(memoryStream);
        memoryStream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.End();
    }
}

所以在大学名单栏中我得到了我要删除的内容。 我尝试过使用TRIM但没有用。 还有其他建议吗?

excel

2 个答案:

答案 0 :(得分:0)

您应该将数据绑定到DataTable(由Scott Hannen建议) 这是一个基于您以前的代码的完整工作示例 我还更新了gridview aspx定义(footertext)以及rowdatabound事件

 public partial class WebForm2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        MyGridView.DataSource = LoadData();
        MyGridView.DataBind();
    }

    private DataTable LoadData()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[6] { new DataColumn("COLLEGE", typeof(string)),
                        new DataColumn("COLLEGE DESC", typeof(string)),
                        new DataColumn("UNDERGRADUATE",typeof(double)),
                        new DataColumn("GRADUATE",typeof(double)),
                        new DataColumn("LAW",typeof(double)),
                        new DataColumn("TOTAL",typeof(double)),
        });
        dt.Rows.Add("AG", "College of Ag Sci and", 1902, 401, 0, 2303);
        dt.Rows.Add("AR", "College of Architecture", 510, 89, 0, 599);
        dt.Rows.Add("AS", "Coll of Arts and Science", 9558, 1281, 0, 10839);
        dt.Rows.Add("BA", "Rawls Coll of Business", 4042, 574, 0, 4616);
        dt.Rows.Add("ED", "College of Education", 823, 1373, 0, 2196);
        dt.Rows.Add("EN", "College of Engineering", 4912, 826, 0, 5738);
        dt.Rows.Add("GR", "Graduate School", 0, 254, 0, 254);
        dt.Rows.Add("HR", "Honors College", 22, 0, 0, 22);
        dt.Rows.Add("HS", "College of Human ...", 2813, 464, 0, 3277);
        dt.Rows.Add("LW", "School of Law", 0, 0, 445, 445);
        dt.Rows.Add("MC", "Coll of Media and ...", 1855, 232, 0, 2087);
        dt.Rows.Add("UN", "Texas Tech University", 3497, 4, 0, 3501);
        dt.Rows.Add("VP", "Coll of Visual and", 803, 316, 0, 1119);


        return dt;

    }

    protected void Export_Click(object sender, EventArgs e)
    {

        using (ExcelPackage excel = new ExcelPackage())
        {

            var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
            workSheet.Cells["J1"].Value = "TEXAS TECH UNIVERSITY";
            workSheet.Cells["J1"].Style.Font.Size = 24;
            workSheet.Cells["J1"].Style.Font.Bold = true;

            workSheet.Cells["I2"].Value = "DEPARTMENT OF INSTITUTIONAL RESEARCH";
            workSheet.Cells["I2"].Style.Font.Size = 20;
            workSheet.Cells["I2"].Style.Font.Bold = true;

            workSheet.Cells["J3"].Value = "test".ToUpper();
            workSheet.Cells["J3"].Style.Font.Bold = true;


            workSheet.Cells["L4"].Value = "(UnCertified Data)";

            workSheet.Cells["A7:F7"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
            workSheet.Cells["A7:F7"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
            workSheet.Cells["A7:F7"].Style.Font.Color.SetColor(System.Drawing.Color.White);

            workSheet.Cells["A21:F21"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
            workSheet.Cells["A21:F21"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
            workSheet.Cells["A21:F21"].Style.Font.Color.SetColor(System.Drawing.Color.White);

            var dt = MyGridView.DataSource as DataTable;
            // add total row to datatable for excel export because rowdatabound event which already calculates total doesn't make total as a part of the datatable at this time
            double totalUnderG = 0;
            double totalGrad = 0;
            double totalLaw = 0;
            double total = 0;
            foreach (var r in dt.Rows.Cast<DataRow>())
            {
                totalUnderG += double.Parse(r[2].ToString());
                totalGrad += double.Parse(r[3].ToString());
                totalLaw += double.Parse(r[4].ToString());
                total += double.Parse(r[5].ToString());
            }
            dt.Rows.Add("TTU TOTAL", "", totalUnderG, totalGrad, totalLaw, total);
            workSheet.Cells[7, 1].LoadFromDataTable(dt, true);


            workSheet.Cells["A7:F7"].AutoFitColumns();

            using (var memoryStream = new MemoryStream())
            {
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=Enrollment_Major_Classification.xlsx");
                excel.SaveAs(memoryStream);
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
            }
        }


    }
    // Declare variable used to store value of Total
    double totalUnderG = 0;
    double totalGrad = 0;
    double totalLaw = 0;
    double total = 0;
    /// <summary>
    /// calculates total when displaying gridview
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        // check row type
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            totalUnderG += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "UNDERGRADUATE"));
            totalGrad += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "GRADUATE"));
            totalLaw += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "LAW"));
            total += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "TOTAL"));
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {

            e.Row.Cells[2].Text = String.Format("{0:N}", totalUnderG);
            e.Row.Cells[3].Text = String.Format("{0:N}", totalGrad);
            e.Row.Cells[4].Text = String.Format("{0:N}", totalLaw);
            e.Row.Cells[5].Text = String.Format("{0:N}", total);

        }
    }


}

和aspx:

  <asp:GridView Width="800px" ID="MyGridView"   AutoGenerateColumns="False" OnRowDataBound="MyGridView_RowDataBound"
    runat="Server"  BorderColor="#555555" HorizontalAlign="Center" 
    Font-Names="Verdana" Font-Size="12px" AllowSorting="True"  ShowFooter="true"
    EmptyDataRowStyle-Font-Bold="true" EmptyDataRowStyle-ForeColor="#CC0000">
            <EmptyDataTemplate>*** No data available ***</EmptyDataTemplate>

    <Columns>
        <asp:BoundField FooterText="TTU TOTAL" HeaderText="COLLEGE" DataField="COLLEGE" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
            ReadOnly="true" DataFormatString="{0:N0}" />
        <asp:BoundField HeaderText="COLLEGE NAME" DataField="COLLEGE DESC" ItemStyle-HorizontalAlign="Left" HeaderStyle-BackColor="#CC0000" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
            ReadOnly="true" DataFormatString="{0:N0}" />
         <asp:BoundField HeaderText="UNDERGRAD" DataField="UNDERGRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
            HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>    
        <asp:BoundField HeaderText="GRAD" DataField="GRADUATE" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
            HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>
        <asp:BoundField HeaderText="LAW" DataField="LAW" ItemStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF" FooterStyle-HorizontalAlign="Right"
            HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>

        <asp:BoundField HeaderText="TOTAL" DataField="TOTAL" ItemStyle-HorizontalAlign="Right" FooterStyle-HorizontalAlign="Right" HeaderStyle-ForeColor="#FFFFFF"
            HeaderStyle-BackColor="#CC0000" ReadOnly="true" DataFormatString="{0:N0}"/>

    </Columns>
</asp:GridView> 
<p>
    <asp:Button ID="Button1" runat="server" OnClick="Export_Click" Text="Export" />
    </p>

aspx page results in browser

excel worksheet screenshot

答案 1 :(得分:0)

我看到您正在重新创建从GridView到Excel文件的样式,这要求在更改GridView样式时,您还必须更改Excel文件的代码。

您可以通过从GridView的HTML表示创建Excel文件来避免这种情况,例如,请参阅以下内容:

protected void ExpToExcel_Click(object sender, EventArgs e)
{
    // Get MyGridView control's HTML representation.
    var plainWriter = new StringWriter();
    var htmlWriter = new HtmlTextWriter(plainWriter);
    this.MyGridView.RenderControl(htmlWriter);

    // Load HTML into ExcelFile.
    SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
    var htmlOptions = new HtmlLoadOptions();
    var htmlStream = new MemoryStream(htmlOptions.Encoding.GetBytes(plainWriter.ToString()));
    var excel = ExcelFile.Load(htmlStream, htmlOptions);

    // Download ExcelFile to current HttpResponse.
    excel.Save(this.Response, "Enrollment_Major_Classification.xlsx");
}

public override void VerifyRenderingInServerForm(Control control)
{
    /* We're overriding this verification because of the "MyGridView.RenderControl" call.
     * This confirms that the "HtmlForm" control is rendered for "MyGridView" at run time. */
}

注意,代码使用GemBox.Spreadsheet库 结果如下:

Exported GridView to Excel file

这样,GridView上的任何更改也会反映在Excel文件中,而不会更改代码。作为一个FYI,我从this article获取了代码。