在Excel C中导出GridView数据时出现问题

时间:2016-08-31 07:42:20

标签: c# asp.net excel gridview

在excel中导出gridview数据时遇到问题。它导出整个页面而不是Gridview数据。

我的代码如下:

        Response.Clear();
        Response.Buffer = true;
        Response.ClearContent();
        Response.ClearHeaders();
        Response.Charset = "";
        StringWriter strwritter = new StringWriter();
        HtmlTextWriter htmlwritter = new HtmlTextWriter(strwritter);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/ms-excel";
        Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", "DSR"+DateTime.Now.ToString("dd-MM-yyyy")+".xls"));
        GridView1.GridLines = GridLines.Both;
        GridView1.HeaderStyle.Font.Bold = true;
        GridView1.RenderControl(htmlwritter);
        Response.Write(strwritter.ToString());
        Response.End();     

5 个答案:

答案 0 :(得分:1)

您可以尝试做类似的事情。简单明了。

    Response.Clear();
    Response.Buffer = true;
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Charset = "";
    StringWriter strwritter = new StringWriter();
    HtmlTextWriter htmlwritter = new HtmlTextWriter(strwritter);
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter strwritter = new StringWriter();
    HtmlTextWriter htmlwritter = new HtmlTextWriter(strwritter);
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/ms-excel";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", "DSR"+DateTime.Now.ToString("dd-MM-yyyy")+".xls"));
    GridView1.RenderBeginTag(htmlwritter);
    GridView1.HeaderRow.RenderControl(htmlwritter);
    foreach (GridViewRow row in GridView1.Rows)
    {
        row.RenderControl(htmlwritter);
    }
    GridView1.FooterRow.RenderControl(htmlwritter);
    GridView1.RenderEndTag(htmlwritter);
    Response.Write(strwritter.ToString());
    Response.End();

答案 1 :(得分:1)

此代码可能会对您有所帮助

        protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        BindData();
        GridView1.Visible = true;

        string FileName = "Deal Report_(" + DateTime.Now.AddHours(5).ToString("yyyy-MM-dd") + ").xls";

        Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition",
         "attachment;filename=" + FileName);
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        GridView1.HeaderRow.Style.Add("color", "#FFFFFF");
        GridView1.HeaderRow.Style.Add("background-color", "#1F437D");

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            row.BackColor = System.Drawing.Color.White;
            row.Attributes.Add("class", "textmode");
            if (i % 2 != 0)
            {
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    //row.Cells[j].Style.Add("background-color", "#eff3f8");
                }
            }
        }
        GridView1.RenderControl(hw);
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.End();
        GridView1.Visible = false;
    }

答案 2 :(得分:0)

解决此问题的一个简单方法是让您的C#代码将GridView 数据源写入Excel文件。

这是我编写的C#库,它完全是这样做的: Export to Excel

所有源代码都是免费提供的,您只需在ASP.Net代码中添加几行:

// The following ASP.Net code gets run when I click on my "Export to Excel" button.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
    // It doesn't get much easier than this...
    CreateExcelFile.CreateExcelDocument(listOfEmployees, "Employees.xlsx", Response);
}

这样做的另一个好处是它可以创造一个真实的&#34; .xlsx文件(使用OpenDocument库)。缺点是那些微软图书馆的重量约为5Mb。

答案 3 :(得分:0)

试试这个,它会起作用..

private void Export_To_Excel()          
{

        Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

        try
        {
            worksheet = workbook.ActiveSheet;

            worksheet.Name = "ExportedFromDatGrid";

            int cellRowIndex = 1;
            int cellColumnIndex = 1;
            ////Loop through each row and read value from each column. 
            for (int i = 0; i < this.dGV.Rows.Count - 1; i++)
            {
                for (int j = 0; j < this.dGV.Columns.Count; j++)
                {
                    //// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check. 
                    if (cellRowIndex == 1)
                    {
                        worksheet.Cells[cellRowIndex, cellColumnIndex] = this.dGV.Columns[j].HeaderText;
                        worksheet.Cells[cellRowIndex, cellColumnIndex].Font.FontStyle = FontStyle.Bold;
                    }
                    else
                    {
                        worksheet.Cells[cellRowIndex, cellColumnIndex] = this.dGV.Rows[i].Cells[j].Value.ToString();
                    }

                    cellColumnIndex++;
                }

                cellColumnIndex = 1;
                cellRowIndex++;
            }

            worksheet.Columns.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            worksheet.Columns.AutoFit();

            ////Getting the location and file name of the excel to save from user. 
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx";
            saveDialog.FilterIndex = 2;

            if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                workbook.SaveAs(saveDialog.FileName);
                MessageBox.Show("Export Successful", "Info", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            }
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
        }
        finally
        {
            excel.Quit();
            workbook = null;
            excel = null;
        }
    }

答案 4 :(得分:0)

这是一个使用EPPlus的示例。只需输入一个SQL查询(或存储过程名称)和一个文件名到exportToExcel,您就会得到一个Excel文件。 exportToExcel("SELECT * FROM yourTable", "myFileName");

    using OfficeOpenXml;
    using OfficeOpenXml.Style;
    using System;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Globalization;
    using System.Web;

    //=== create an excel document =========================================
    public static void exportToExcel(string sqlQuery, string fileName)
    {
        HttpResponse Response = HttpContext.Current.Response;
        DataTable dt = loadExternalDataTable(sqlQuery);

        using (ExcelPackage p = new ExcelPackage())
        {
            //create a new workbook
            p.Workbook.Properties.Author = "VDWWD";
            p.Workbook.Properties.Title = fileName;
            p.Workbook.Properties.Created = DateTime.Now;

            //create a new worksheet
            p.Workbook.Worksheets.Add(fileName);
            ExcelWorksheet ws = p.Workbook.Worksheets[1];
            ws.Name = fileName;
            ws.Cells.Style.Font.Size = 11;
            ws.Cells.Style.Font.Name = "Calibri";

            createExcelHeader(ws, dt);
            createExcelData(ws, dt);

            ws.Cells[ws.Dimension.Address].AutoFitColumns();

            //make all columms just a bit wider, they would sometimes not fit
            for (int col = 1; col <= ws.Dimension.End.Column; col++)
            {
                ws.Column(col).Width = ws.Column(col).Width + 1;
            }

            //send the file to the browser
            byte[] bin = p.GetAsByteArray();
            Response.ClearHeaders();
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-length", bin.Length.ToString());
            Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".xlsx\"");
            Response.OutputStream.Write(bin, 0, bin.Length);
            Response.Flush();
            Response.Close();
            Response.End();
        }
    }


    //=== create the excel sheet header row =========================================
    private static void createExcelHeader(ExcelWorksheet ws, DataTable dt)
    {
        int colindex = 1;

        //loop all the columns
        foreach (DataColumn dc in dt.Columns)
        {
            var cell = ws.Cells[1, colindex];

            //make the text bold
            cell.Style.Font.Bold = true;

            //make the background of the cell gray
            var fill = cell.Style.Fill;
            fill.PatternType = ExcelFillStyle.Solid;
            fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF"));

            //fill the cell with the text
            cell.Value = dc.ColumnName.ToUpper();

            colindex++;
        }
    }


    //=== create the excel sheet data =========================================
    private static void createExcelData(ExcelWorksheet ws, DataTable dt)
    {
        int colindex = 0;
        int rowindex = 1;

        //loop all the rows
        foreach (DataRow dr in dt.Rows)
        {
            colindex = 1;
            rowindex++;

            //loop all the columns
            foreach (DataColumn dc in dt.Columns)
            {
                var cell = ws.Cells[rowindex, colindex];
                string datatype = dc.DataType.ToString();

                //fill the cell with the data in the correct format, needs to be done here because the headder row makes every column a string otherwise
                if (datatype == "System.Decimal" || datatype == "System.Double" || datatype == "System.Float")
                {
                    if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                        cell.Value = Convert.ToDecimal(dr[dc.ColumnName]);

                    cell.Style.Numberformat.Format = "0.00";
                }
                else if (datatype == "System.Int16" || datatype == "System.Int32" || datatype == "System.Int64" || datatype == "System.Long")
                {
                    if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                        cell.Value = Convert.ToInt64(dr[dc.ColumnName]);
                }
                else if (datatype == "System.Bool" || datatype == "System.Boolean")
                {
                    if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                        cell.Value = Convert.ToBoolean(dr[dc.ColumnName]); ;
                }
                else if (datatype == "System.DateTime")
                {
                    if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                        cell.Value = Convert.ToDateTime(dr[dc.ColumnName]);

                    cell.Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
                }
                else
                {
                    cell.Value = dr[dc.ColumnName];
                }

                colindex++;
            }
        }
    }


    //=== create a datatable from a query  =========================================
    public static DataTable loadExternalDataTable(string sqlQuery)
    {
        DataTable dt = new DataTable();

        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
        using (SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, connection))
        {
            try
            {
                adapter.Fill(dt);
            }
            catch
            {
            }
        }

        return dt;
    }