2014-10-24 3 views
0

Excel 2007에 gridview를 내보내고 싶습니다. mime type application/vnd.ms-excel (excel 2003)을 사용하여 2007 년 Excel 2007로 가져올 수있는 코드를 가져올 수 있지만 경고 메시지가 나타납니다. "당신이 열려고하는 파일이 다른 형식입니다 ..."라고 말하면 yes와 no를 사용하여 clic을 클릭하고 예를 들어 파일을 클릭하면 고객을 위해 msg를 가질 수 없습니다. 그리고 mime을 사용합니다 excel 2007 (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet) 파일을 열면 "Excel에서 형식이나 확장이 유효하지 않기 때문에 파일을 열 수 없습니다."라는 메시지가 나타납니다. GridView를 Excel 2007로 내보내기

내가 지금 코드를 사용하고 있습니다 :

using System; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.IO; 
using System.Drawing; 


namespace TesteFornecedores 
{ 
    public partial class Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!this.IsPostBack) 
      { 
       this.BindGrid(); 
      } 
     } 

     private void BindGrid() 
     { 
      using (DataSet ds = new DataSet()) 
      { 
       ds.ReadXml(Server.MapPath("~/Customers.xml")); 
       GridView1.DataSource = ds; 
       GridView1.DataBind(); 
      } 
     } 


     protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e) 
     { 
      GridView1.PageIndex = e.NewPageIndex; 
      this.BindGrid(); 
     } 




     protected void ExportToExcel(object sender, EventArgs e) 
     { 
      Response.Clear(); 
      Response.Buffer = true; 
      Response.AddHeader("content-disposition", "attachment; filename=ExcelList"); 
      Response.Charset = ""; 
      Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
      using (StringWriter sw = new StringWriter()) 
      { 
       HtmlTextWriter hw = new HtmlTextWriter(sw); 

       //To Export all pages 
       GridView1.AllowPaging = false; 
       this.BindGrid(); 

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

       GridView1.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(); 
      } 
     } 

     public override void VerifyRenderingInServerForm(Control control) 
     { 
      /* Verifies that the control is rendered */ 
     } 
    } 
} 

사람은 2007이있는 gridview Excel에서 나를 열어 도움을 줄 수있는 솔루션을 알아?

감사합니다.

답변

0

실제 Excel 형식으로 내보낼 수 없습니다. HTML 파일을 만드는 중이며 Excel에서 처리 방법을 알고있는 MIME 형식을 제공하고 있으므로 Excel에서이를 열려고 시도합니다. Excel은 기본 HTML 파일을 읽는 방법을 알고 있지만 서식을 제어하기는 어려우며 경고 메시지가 표시됩니다.

대신에 .xlsx 파일을 생성하려면 필요한 파일을 생성 할 수있는 라이브러리를 사용해야합니다. 이 예는 EPPlusOpen Office XML SDK입니다. Microsoft는 서버 측에서 지원하지 않으므로 Excel Interop 기반 솔루션을 사용하지 않아도되므로 디버그하기가 어려워 두통을 유발할 수 있습니다.

그런데 "GridView를 내보내는 것"이라고 생각하지 마십시오. 그것은 나쁜 접근법입니다. GridView는 HTML로 데이터를 표시하기위한 UI 요소입니다. 대신이 데이터를 어떻게 내 보내야합니까?라고 생각하십시오. 귀하의 경우에는 DataSet 또는 XML 유형 데이터를 내보내는 것으로 간주하십시오.

0
 Response.Clear(); 
     Response.ContentType = "application/excel"; 
     Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); 
     Response.BinaryWrite(objectData);//objectData is binary data 
     Response.End(); 

귀하의 답변은 다음과 같아야합니다. 응답에 유효한 엑셀 파일을주지 않으므로 코드가 작동하지 않을 것이라고 확신합니다. OleDbConnection

그리드의 DataSource에서 데이터 세트를 사용하십시오. 그 후

OleDbConnection conn = new OleDbConnection(); 


string connectString = String.Format(
        "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR={1};'", 
        fileName, "YES"); 

       conn.ConnectionString = connectString; 
       conn.Open(); 

OleDbCommand comm = new OleDbCommand(); 
comm.CommandText = string.Format("CREATE TABLE [{0}] ", "TableName"); 

OleDbConnection가 comm.CommanText에 DataSet에서 열을 추가 구축 할 수 있습니다. dataSet 열 구조의 복제본을 작성하려면. 그 후 :

comm.Connection = conn; 
comm.ExecuteNonQuery(); 

이제 데이터 세트와 같은 열로 만들어진 표가 생성되었습니다.

이제

  OleDbDataAdapter ad = new OleDbDataAdapter(
       string.Format("SELECT * FROM [{0}]", "TableName"), conn); 
      OleDbCommandBuilder builder = new OleDbCommandBuilder(ad); 
      builder.QuotePrefix = "["; 
      builder.QuoteSuffix = "]"; 

      // Saves the data set 
      ad.Update(DataSetFromTheGrid); 

는 이제 데이터로 테이블을 가득 컨텐츠를 업데이트해야합니다. // 인식 할 fileName은 연결 문자열의 fileName과 같습니다! FileStream fs = 새 FileStream (fileName, FileMode.Open, FileAccess.Read);

  BinaryReader reader = new BinaryReader(fs); 
      excelBytes = reader.ReadBytes((int)fs.Length); 
      //after the returned bytes it will be good to delete the file ! 

이 바이트를 응답에 반환하면 엑셀 파일이 생깁니다.

관련 문제