使用Web API和Angular2导出到Excel

时间:2017-03-27 06:57:25

标签: angular epplus

我有错误(文件已损坏),而导出到Excel但从控制台上的Web API数组返回

Web API操作

[HttpPost]
        public FileResult ParentGridExportToExcel([FromBody]PromoDetail value)
        {      
            var result = this._promodetailReportEngineRepository.ParentGridExportToExcel(promodetail);
            DataTable table = this.ConvertListToDataTable(result.PromoList);
            DataSet ds = new DataSet();
            ds.Tables.Add(table);
          return  this.ExportDataSetToExcel(ds, dt, false);

        }

    private FileResult ExportDataSetToExcel(DataSet ds, DataTable dt)
        {

            using (var xp = new ExcelPackage())
            {
                var ws = xp.Workbook.Worksheets.Add("Stores");
                ws.Cells[10, 1].LoadFromDataTable(dt, true);
                ws.Cells[35, 1].LoadFromDataTable(ds.Tables[0], true);    
                ws.Cells[ws.Dimension.Address].AutoFitColumns();    
                //xp.Save();
                return this.File(
                                xp.GetAsByteArray(),
                                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                                "PromoDetail10.xlsx");

            }
        }

Angular 2 Component方法 - 我使用文件保存保存程序来保存Excel文件

  parentGridExportToExcel()
{
  this._promoapi.parentGridExportToExcel(this.pageSize, this.currentPageOffset, this.datewiseCalendarAttribute)
            .subscribe(
                res => {
                        this.extractData(res);
                }
            );


}
extractData(res: any){
       let myBlob: Blob = new Blob([(<any>res)._body], {type: 'vnd.openxmlformats-officedocument.spreadsheetml.sheet'}); // replace the type by whatever type is your response
    var fileURL = URL.createObjectURL(myBlob);
console.log(res);
            saveAs(myBlob, 'PromoDetail10.xlsx');
}

Angular 2服务

parentGridExportToExcel(pageSize: number, currentPageOffset: number)
    {
        let body = JSON.stringify({ Pagesize: pageSize,DatewiseCalendarAttribute: datewiseCalendarAttribute});
        let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8','responseType':'blob' });
        let options = new RequestOptions({
            headers: headers
        })      
        return this._http.post(this.baseUrl + 'ParentGridExportToExcel',body,options)
            .map(res => res)    
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError)
    }

0 个答案:

没有答案