2014-10-28 2 views
3

AngularJS & ASP.NET MVC를 사용하여 다운로드 가능한 Excel 컨텐츠로 내보내는 데 문제가 있습니다. 내 최종 결과는 아무 일도 일어나지 않습니다.Excel로 내보내기

샘플 ASP.NET 컨트롤러 방법 :

[HttpPost] 
public ActionResult ExportToExcel(Model form) 
{ 
    var gv = new GridView(); 
    gv.DataSource = _service.getSomeStuff(form); 
    gv.DataBind(); 
    Response.ClearContent(); 
    Response.Buffer = true; 
    Response.AddHeader("content-disposition", "attachment; filename=Stuff.xls"); 
    Response.ContentType = "application/ms-excel"; 
    Response.Charset = ""; 
    var sw = new StringWriter(); 
    var htw = new HtmlTextWriter(sw); 
    gv.RenderControl(htw); 
    Response.Output.Write(sw.ToString()); 
    Response.Flush(); 
    Response.End(); 

    byte[] temp = System.Text.Encoding.UTF8.GetBytes(sw.ToString()); 
    return File(temp, "application/ms-excel"); 
} 

각도 컨트롤러 방법 : ->를 통해 트리거 핸들러 NG는 클릭

function exportToExcel() { 
    $http.post('/Controller/ExportToExcel/', vm.Model) 
      .success(function (data) { 
      }) 
      .error(function (data) { 
       alerts.error(data); 
      }); 
} 

보기 : 무엇

<a href="" ng-click="vm.exportToExcel()">click me</a> 

어떤 제안 내가 잘못하고있는 것일까?

+1

File을 반환하기 전에'Response.End()'를 호출합니다. 나는 그 문제가 – DLeh

+0

@ user167698 인 원인이 상상해보십시오. Response.ClearContent(); Response.Buffer = true; Response.AddHeader ("content-disposition", "attachment; filename = Stuff.xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; var sw = new StringWriter(); var htw = 새 HtmlTextWriter (sw); gv.RenderControl (htw); Response.Output.Write (sw.ToString()); Response.Flush(); Response.End(); ' \t 또는'byte [] temp = System.Text.Encoding.UTF8.GetBytes (sw.ToString()); 반환 파일 (temp, "application/ms-excel");'. 둘 다 사용하지 마십시오. – yW0K5o

+0

아쉽게도 Response.End()를 사용하거나 사용하지 않고 시도했습니다. 결과에는 차이가 없습니다. "ExportToExcel (Model form)"메소드는 표준 양식 제출에서 호출 된 경우 다운로드를 생성하는 것으로 보입니다. – user167698

답변

0

저는 AJAX 나 JS가 필요없이 이런 식으로했습니다. 면도기 코드를 조정하는 것만으로도 충분합니다.

둘째, 제 개인적인 제안은 Excel 파일로 변환하지 않는 것입니다. 그 이유는 사용자가 로컬 컴퓨터에 Office가 있어야하기 때문입니다. 또한 프로젝트를 웹 사이트에 업로드하면 Excel 컴퓨터에서 Excel 파일을 생성하기 위해 Office 서버가 설치되어 있어야합니다.

즉, 나는 단지 CSV 파일을 사용하는 것이 좋습니다. 사용자가 Office를 설치 한 경우 Excel을 사용하여 스프레드 시트처럼 파일을 볼 수 있습니다.

StringBuilderReflection을 사용하여 dbcontext의 dbset에서 Export.csv라는 CSV 파일을 만드는 일부 코드는 다음과 같습니다. 이 도움이

<a href="@Url.Action("Export", "Controller")">click me</a> 

희망 :

public ActionResult Export() 
    { 
     StringBuilder str = new StringBuilder(); 
     var tmp = db.Users.FirstOrDefault();  
     Type comp = tmp.GetType();    // get type 
     foreach (PropertyInfo prop in comp.GetProperties()) 
     { 
      str.Append(prop.Name + ",");   //set column names 
     } 
     str.Replace(",", "\n", str.Length - 1, 1); 
     foreach (object item in db.Users) 
     { 
      foreach (PropertyInfo prop in item.GetType().GetProperties()) 
      { 
       try 
       { 
        string a = prop.GetValue(item, null).ToString(); 
        str.Append(a + ","); 
       } 
       catch (NullReferenceException) 
       { 
        str.Append("null" + ",");   //for nulls, append string with "null" 
       } 
      } 
      str.Replace(",", "\n", str.Length - 1, 1); 
     } 
     string csv = str.ToString(); 
     return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv"); 
    } 

당신은 다음과 같은보기에 링크 파일을 다운로드에 액세스 할 수 있습니다.

+0

감사합니다. 이것은 잘 작동합니다. :-) – user167698

+0

환영합니다 :) – AbdulG