2014-02-05 2 views
1

나는 다음과 같이 엑셀 기능을 내보내기를 사용했다 : getReport 테이블 형식으로 데이터를 반환수출은 기존의 엑셀 템플릿을 사용하여 Excel로

var table = getReport(param1, param2, param3); 
      Response.ClearContent(); 
      Response.AddHeader("content-disposition", "attachment;filename=Report.xls"); 
      Response.ContentType = "application/vnd.ms-excel"; 
      System.Web.UI.WebControls.GridView grd = new System.Web.UI.WebControls.GridView(); 
      grd.DataSource = table; // give datasource here 
      grd.DataBind(); 
      StringWriter swr = new StringWriter(); 
      HtmlTextWriter tw = new HtmlTextWriter(swr); 
      grd.RenderControl(tw); 
      Response.Write(swr.ToString()); 
      Response.End(); 
      return View(); 

. 이제 새로운 Excel 파일이 만들어 지지만 기존 Excel 템플릿을 사용하여 Excel 출력을 만들고 싶습니다. 프로젝트에 템플릿을 추가하는 방법과 데이터를 바인딩하는 방법?

답변

0

사용중인 접근 방식은 응답에 HTML 문자열을 쓰고 응답 헤더에 ContentType을 Excel로 설정하는 것입니다. 이것은 실제 Excel 파일을 만들지 않고, 브라우저가 Excel에서 파일을 시작하도록하고 Excel은 HTML 파일을 처리 할 수 ​​있습니다. 이 방법으로 템플릿을 추가 할 방법이 없습니다.

기존 Excel 파일을 템플릿으로 사용하려면 OfficeWriter과 같은 실제 Excel 파일을 만들고 수정할 수있는 API를 사용해야합니다. 다음은 OfficeWriter를 사용하여 DataTable을 템플릿 파일에 직접 바인딩하는 방법의 예입니다.

using SoftArtisans.OfficeWriter.ExcelWriter;  

ExcelTemplate xlt = new ExcelTemplate(); 
//Open the template file 
xlt.Open(pathToTemplateFile); 
//Create a DataBindingProperties object 
DataBindingProperties props = xlt.CreateDataBindingProperties(); 
// Call the BindData method, passing the DataTable and a name for the datasource 
// which will be referenced in the "data markers" in the template 
xlt.BindData(table, "DataSource1", props); 
//Call the Process method, which binds the data and generates the output file 
xlt.Process(); 
//Stream the file to the Response 
xlt.Save(Response, "Report.xls", false); 

면책 조항 : 나는, SoftArtisans에 대한 OfficeWriter

의 제조 업체를 작동
관련 문제