2016-06-21 4 views
0

GridView을 엑셀 파일로 내보내는 데 아래 코드가 있습니다. 이론적으로이 코드는 번거 로움없이 내보내기해야합니다. 그러나 빈을 내보내는 중입니다.엑셀로 내보내기 엑셀로 돌아 가기 빈 엑셀 스프레드 시트

public static void Export(string fileName, GridView gv, System.Web.UI.Control parentControl) 
    { 
     HttpContext.Current.Response.Clear(); 
     HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename=" + fileName + ".xls")); 
     HttpContext.Current.Response.ContentType = "application/ms-excel"; 

     using (StringWriter sw = new StringWriter()) 
     { 
      using (HtmlTextWriter htw = new HtmlTextWriter(sw)) 
      { 
       // Create a table to contain the grid 
       Table table = new Table(); 

       // include the gridline settings 
       table.GridLines = gv.GridLines; 

       // add the header row to the table 
       if (gv.HeaderRow != null) 
       { 
        GridViewExportUtil.PrepareControlForExport(gv.HeaderRow); 
        table.Rows.Add(gv.HeaderRow); 
       } 

       // add each of the data rows to the table 
       foreach (GridViewRow row in gv.Rows) 
       { 
        GridViewExportUtil.PrepareControlForExport(row); 
        table.Rows.Add(row); 
       } 

       // add the footer row to the table 
       if (gv.FooterRow != null) 
       { 
        GridViewExportUtil.PrepareControlForExport(gv.FooterRow); 
        table.Rows.Add(gv.FooterRow); 
       } 

       //Control 'Content_ctlDisplayIssues_gvIssues' of type 'GridView' must be placed inside a form tag with runat=server. 
       System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm(); 
       parentControl.Controls.Add(form); 
       form.Controls.Add(gv); 
       form.RenderControl(htw); 

       // render the htmlwriter into the response 
       HttpContext.Current.Response.Write(sw.ToString()); 
       HttpContext.Current.Response.End(); 
      } 
     } 
    } 

    /// <summary> 
    /// Replace any of the contained controls with literals 
    /// </summary> 
    /// <param name="control"></param> 
    private static void PrepareControlForExport(Control control) 
    { 
     for (int i = 0; i < control.Controls.Count; i++) 
     { 
      Control current = control.Controls[i]; 
      if (current is LinkButton) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); 
      } 
      else if (current is ImageButton) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); 
      } 
      else if (current is HyperLink) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); 
      } 
      else if (current is DropDownList) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); 
      } 
      else if (current is CheckBox) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); 
      } 
      else if (current is Image) 
      { 
       control.Controls.Remove(current); 
       control.Controls.AddAt(i, new LiteralControl((current as Image).AlternateText)); 
      } 

      if (current.HasControls()) 
      { 
       GridViewExportUtil.PrepareControlForExport(current); 
      } 
     } 
    } 
} 

나는 여기에 뭔가가 없습니까?

+0

2 일 나는 '1 변화 당신의 경우 ASP Response.ContentType = "application/vnd.ms-엑셀"을 발견; '도움이되는지 확인하면 헤더를 추가하기 전에 – MethodMan

+0

도 다음을 추가합니다. 'HttpContext.Current.Response.ClearContent(); 그리고 HttpContext.Current.Response.ClearHeaders();'이 줄을 추가하십시오. – MethodMan

+0

내가 그걸 줘 보자. –

답변

0

코드의 대부분이 정확합니다. 여기서 문제는 HTML Writer가 올바르게 렌더링되지 않는다는 것입니다. John Wu 그의 대답에 이것을 언급했다. 여기 둘러보기는 간단합니다 :

대신;

//Control 'Content_ctlDisplayIssues_gvIssues' of type 'GridView' must be placed inside a form tag with runat=server. 
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm(); 
parentControl.Controls.Add(form); 
form.Controls.Add(gv); 
form.RenderControl(htw); 

나는 사용했다;

//here the table is rendered into the html writer 
table.RenderControl(htw); 

도 중요, 이것은 나를 위해 완벽하게 일을 Web.config 파일

<add key="PageInspector:ServerCodeMappingSupport" value="Disabled" /> 

에이 코드를 추가하는 것입니다. `이 `2nd` Current.Response.End 전에 (`HttpContext.Current.Response.Flush 넣어)

0

메모장에 Excel 파일을 여는 적이 있습니까? 그 안에 HTML이 아닙니다! 그러나 HtmlTextWriter를 사용하여 데이터를 브라우저로 스트리밍합니다. 나는 그것이 작동 할 것이라고 생각하지 않는다.

데이터를 Excel 네이티브 형식으로 변환하려고 결정한 경우 Excel interop을 사용하거나보다 효율적인 타사 변환 도구를 사용할 수 있습니다.

사용자가 Excel에서 스프레드 시트를 열면되지만 데이터가 브라우저로 전송되는 방법은 신경 쓰지 않으면 this article과 같은 기술을 사용하여 CSV 형식으로 데이터를 스트리밍하는 것이 좋습니다. .

관련 문제