2014-05-21 51 views
0

我對asp.net開發很新穎如何在asp.net中創建excel文件?

我已經提出用戶下載按鈕點擊excel格式的asp repeater grid details。我曾與下面的代碼做了我使用Google

  Response.Clear(); 
      Response.Buffer = true; 
      Response.AddHeader("content-disposition", "attachment;filename=ExcelExport.xls"); 

      for (int i = 0; i < RptMasterData.Items.Count; i++) 
      { 
       Table tbl = (Table)RptMasterData.Items[i].FindControl("tblTest"); 
       tbl.Style.Add("background-color", "#FF9900"); 
       GridView gvAllocation = (GridView)RptMasterData.Items[i].FindControl("gvAllocation"); 
       gvAllocation.HeaderRow.Style.Add("background-color", "#95c556"); 

       int j = 1; 
       foreach (GridViewRow gvrow in gvAllocation.Rows) 
       { 
        gvAllocation.BackColor = System.Drawing.Color.White; 
        if (j <= gvAllocation.Rows.Count) 
        { 
         if (j % 2 != 0) 
         { 
          for (int k = 0; k < gvrow.Cells.Count; k++) 
          { 
           gvrow.Cells[k].Style.Add("background-color", "#EFF3FB"); 
          } 
         } 
        } 
        j++; 
       } 
      } 

      Response.ContentType = "application/vnd.ms-excel"; 
      Response.ContentEncoding = System.Text.Encoding.Unicode; 
      Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); 

      StringWriter sw = new StringWriter(); 
      HtmlTextWriter hw = new HtmlTextWriter(sw); 

      //style to format numbers to string 
      string style = @"<style> .textmode { mso-number-format:\@; } </style>"; 
      Response.Write(style); 
      RptMasterData.RenderControl(hw); 
      Response.Write("<table>"); 
      Response.Output.Write(sw.ToString()); 
      Response.Write("<table>"); 
      Response.Flush(); 
      HttpContext.Current.ApplicationInstance.CompleteRequest(); 
      Response.Close(); 

文件下載爲Excel file.But當我嘗試打開MS辦公文件,我得到的

enter image description here

錯誤消息後得到

當我嘗試編輯並保存Ms-office中的文件時發生問題。然後,它顯示以下警告
enter image description here

所以我只是試圖在文本編輯器打開相同,發現下載的文件是一個包含所需要的數據無法按預期Excel文件的HTML文件。

任何人都可以引導我如何創建一個下載時用戶點擊一個實際的Excel文件「下載」

回答