2016-07-27 136 views
-2

我正在将一个GridView导出到一个Excel文件,但是当我打开这个文件时,首先我得到一个关于格式类型和扩展名不匹配的错误,当我打开它时,整个页面被带入Excel文件,而不仅仅是网格视图。如何将GridView导出到Excel?

enter code here 

    protected void ExportToExcel(object sender, EventArgs e) 
     { 
      try 
      { 
       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 
        gridCustomer.AllowPaging = false; 
        //this.gridCustInfoBind(1); 
        gridCustAllInfoBind(1); 

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

        gridCustomer.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(); 
       } 
      } 
      catch (Exception ex) 
      { 
       ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Exception Message: " + ex.Message.Replace("'", "").Replace("\"", "") + "');", true); 
      } 
     } 
+0

因为生成的文件内容的.html不.xls的 – Slai

+0

如何将其转化为.xls的,你可以修改我的代码。 –

回答

0

看看doodlereport nuget包,我认为它会为你工作。

0

下面的代码将您的数据表转换到Excel,所以你可以用它代替:

public void CreateExcel(DataTable dt, string path) 
    { 

     try 
     { 
      if (File.Exists(path)) 
       File.Delete(path); 

      FileInfo newFile = new FileInfo(path); 
      using (ExcelPackage pck = new ExcelPackage(newFile)) 
      { 
       //Create the worksheet 
       ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Query Result"); 

       //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1 
       //ws.Cells["A1"].LoadFromDataTable(dt, true); 
       //ws.Cells["A1"].AutoFitColumns(); 

       int columnNumber = 0; 
       foreach (DataColumn dc in dt.Columns) 
       { 
        columnNumber++; 
        ws.Cells[1, columnNumber].Value = dc.ColumnName; 
       } 

       //Adding data of each row. 
       int rowNumber = 0; 
       foreach (DataRow rw in dt.Rows) 
       { 
        rowNumber++; 

        columnNumber = 0; 
        foreach (DataColumn dc in dt.Columns) 
        { 
         columnNumber++; 
         //Formating columns based on data types 
         if (rw[dc.ColumnName].GetType().ToString() == "System.Int32" || rw[dc.ColumnName].GetType().ToString() == "System.Double") 
          ws.Cells[rowNumber + 1, columnNumber].Style.Numberformat.Format = "0"; 
         else if (rw[dc.ColumnName].GetType().ToString() == "System.DateTime") 
          ws.Cells[rowNumber + 1, columnNumber].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss"; 
         else if (rw[dc.ColumnName].GetType().ToString() == "System.Decimal") 
          ws.Cells[rowNumber + 1, columnNumber].Style.Numberformat.Format = "0.00"; 

         ws.Cells[rowNumber + 1, columnNumber].Value = rw[dc.ColumnName]; 
        } 
       } 


       //Format the header for columns 
       using (ExcelRange rng = ws.Cells["A1:Z1"]) 
       { 
        rng.Style.Font.Bold = true; 

       } 

       //Format Cells 
       using (ExcelRange col = ws.Cells[2, 1, dt.Rows.Count + 1, dt.Columns.Count + 1]) 
       { 
        col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right; 
        col.Style.VerticalAlignment = ExcelVerticalAlignment.Center; 
        col.AutoFitColumns(); 
       } 

       //Saving the excel sheet 
       pck.Save(); 
      } 

     } 
     catch (Exception ex) 
     { 
     } 



    }