簡體   English   中英

將OpenXML創建的Excel電子表格導出到客戶端

[英]Exporting OpenXML created Excel Spreadsheet to client side

我正在嘗試獲取API,以開始下載已創建的excel電子表格。 雖然,我似乎遇到了一些麻煩。 我也嘗試過將電子表格內存流的字節數組發送到前端,然后從那里去,但是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);
}

然后獲取我的文件以下載客戶端。

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

您需要告訴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);
}

您的“返回ms.ToArray();” 行需要在使用中移動,並可能添加“ document.Close();”:

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
            ...

            //Styling the doucment
            ...

            //Adding width to the columns
            ...

            //Creating the worksheet part to add the data to
            ...

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

            //Creating the first Header Row
            ...

            //Appending the data into their respective columns 
            foreach (var ent in barBillExport)
            {
                ...
            }

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM