将OpenXML创建的Excel电子表格导出到客户端 - c#

我正在尝试获取API,以开始下载已创建的excel电子表格。虽然,我似乎遇到了一些麻烦。我也尝试过将电子表格内存流的Byte数组发送到前端,然后从那里去,但是excel文件已损坏并且不包含任何数据。

控制器:

    [HttpPost]
    [Route("CreateExcelDocument")]
    public ActionResult CreateExcelDocument([FromBody] List<BarBillList> model)
    {
        try
        {
            byte[] tmp;
            using (ExcelController ex = new ExcelController())
            {
                tmp = ex.createExcelSpreadsheet(barBillExport);
            }

            string fileName = "xxx.xlsx";
            return File(tmp, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }
        catch (Exception e)
        {
            return null;
        }
    }

具有电子表格创建方法的ExcelController类:

 public byte[] createExcelSpreadsheet(List<BarBillList> barBillExport)
    {
        DateTime today = DateTime.Today;
        using (MemoryStream ms = new MemoryStream())
        {
            using (SpreadsheetDocument document = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
            {
                //Creating the initial document
                WorkbookPart workbookPart = document.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();

                WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                worksheetPart.Worksheet = new Worksheet();

                workbookPart.Workbook.Save();

                //Styling the doucment
                WorkbookStylesPart stylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
                stylesPart.Stylesheet = GenerateStyleSheet();
                stylesPart.Stylesheet.Save();

                //Adding width to the columns
                DocumentFormat.OpenXml.Spreadsheet.Columns columns = new DocumentFormat.OpenXml.Spreadsheet.Columns();
                columns.Append(new DocumentFormat.OpenXml.Spreadsheet.Column() { Min = 1, Max = 6, Width = 20, CustomWidth = true });
                worksheetPart.Worksheet.Append(columns);

                //Creating the worksheet part to add the data to
                Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
                Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "BarBill" };
                sheets.Append(sheet);

                SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());

                //Creating the first Header Row
                Row row = new Row();
                row.Append(
                    ConstructCell("Name", CellValues.String, true),
                    ConstructCell("Last Payment Date", CellValues.String, true),
                    ConstructCell("Last Payment Amount", CellValues.String, true),
                    ConstructCell("Current Balance", CellValues.String, true));

                sheetData.AppendChild(row);

                //Appending the data into their respective columns 
                foreach (var ent in barBillExport)
                {
                    row = new Row();

                    row.Append(
                        ConstructCell(ent.Name.ToString(), CellValues.String, false),
                        ConstructCell((ent.LastPaymentDate.ToString().Length > 0) ? ent.LastPaymentDate.ToString() : "", CellValues.String, false),
                        ConstructCell((ent.LastPayment.ToString().Length > 0) ? ent.LastPayment.ToString() : "", CellValues.String, false),
                        ConstructCell((ent.TotalBalance.ToString().Length > 0) ? ent.TotalBalance.ToString() : "", CellValues.String, false));
                    sheetData.AppendChild(row);
                }

                worksheetPart.Worksheet.Save();
            }
            return ms.ToArray();
        }
    }

编辑

前端服务:

    createExcelDocument(model: BillList[]): any {
    return this.http.post(this.getBarBillsUrl + "/CreateExcelDocument", model)
        .map(this.helper.extractData)
        .catch(this.helper.handleError);
}

我知道映射器不需要在那里。但是我将其保留在那里应该将字节数组传递到前面并从那里开始。

对此事的任何指导或指导将不胜感激。

谢谢。

为有兴趣或面临类似问题的人找到解决方案(请参阅以下作者答案)

我将{ responseType: ResponseContentType.Blob }添加到TypeScript中的服务调用中。

然后,它给我返回了电子表格的内容。从那里,我在打字稿中通过另一种方法运行它:

    private saveAsBlob(data: any) {
    const year = this.today.getFullYear();
    const month = this.today.getMonth();
    const date = this.today.getDate();
    const dateString = year + '-' + month + '-' + date;

    const file = new File([data], 'BarBill ' + dateString + '.xlsx',
        { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

    FileSaver.saveAs(file);
}

然后获取我的文件以下载客户端。

非常感谢大家。尤其是答案的作者。

c#大神给出的解决方案

您需要告诉Angular响应不是JSON格式,因此它不会尝试解析它。尝试将代码更改为:

  createExcelDocument(model: BillList[]): any {
    return this.http.post(this.getBarBillsUrl + "/CreateExcelDocument", 
            model,  { responseType: ResponseContentType.Blob })
        .map(this.helper.extractData)
        .catch(this.helper.handleError);
}

上面的代码为二进制格式,但是对于excel文件,您应该使用以下代码:

const httpOptions = {
      headers: new HttpHeaders({ 'responseType':  'ResponseContentType.Blob',
      'Content-Type':  'application/vnd.ms-excel'})};

  createExcelDocument(model: BillList[]): any {
    return this.http.post(this.getBarBillsUrl + "/CreateExcelDocument", 
            model, httpOptions )
        .map(this.helper.extractData)
        .catch(this.helper.handleError);
}

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

jQuery DataTable TableTool在IE和Firefox中不起作用 - c#

我在MVC4 ASP.NET Web应用程序中使用Jquery DataTable TableTool。导出到Excel和PDF可以与Chrome完美配合。但是不能在IE和FireFox中使用。我的代码如下 dom: 'T<"clear">lfrtip', tableTools: { "sSwfP…

Mongo汇总 - javascript

我的收藏中有以下文件{ "_id": ObjectId("54490b8104f7142f22ecc97f"), "title": "Sample1", "slug": "samplenews", "cat": …

字符串文字中的正斜杠表现异常 - python

为什么S1和S2在撇号位置方面表现不同?S1="1/282/03/10" S2="4/107/03/10" R1="".join({"N\'" ,S1,"\'" }) R2="".join({"N\'…

Ajax功能后没有数据传递到URL - javascript

这是我使用Ajax将参数传递到另一个PHP页面的脚本。 $(document).on( "click",".btndriver", function() { var id = $(this).attr("id"); var nombre = $(this).attr("nombre…