2016-07-27 2 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

아래의 코드는 엑셀에 데이터 테이블을 변환합니다, 그래서 당신은 대신 사용할 수 있습니다 :

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



    } 
관련 문제