簡體   English   中英

Asp.net WebApi Aspose.Cells - 導出和下載 excel

[英]Asp.net WebApi Aspose.Cells - export and download excel

我使用 Aspose.Cells 創建 excel 文件。

實際上我正在嘗試將 xls 文件保存在磁盤上,但我無法解決這個問題。 這是我的獲取方法。

[Route("xls")]
    [HttpGet]
    public HttpResponseMessage Export()
    {
        try
        {
            string dataDir = KnownFolders.GetPath(KnownFolder.Downloads);
            //var workbook = TransferService.Export();  //TODO get xml
            Workbook workbook = new Workbook();              
            var stream = workbook.SaveToStream();   

            // I need save this workbook

            return Request.CreateResponse(HttpStatusCode.OK); //it's not important here
        }
        catch (Exception ex)
        {

            return Request.CreateResponse(HttpStatusCode.InternalServerError); //it's not important here
        }
    }

我還有 function 稱為 onClick

function exportToXls() {
    $.get(exportURI, function (response) {
        return response;
    });
}

當有人點擊它時,它應該將文件保存在他的磁盤上(或打開瀏覽器,我可以在其中選擇位置和名稱)。 如何解決這個問題?

C#

    [Route("xls")]
    [HttpPost] // can use Get, but Post seems to be recommended
    public HttpResponseMessage Export()
    {
        var response = new HttpResponseMessage();

        try
        {
            // Create workbook
            var wb = new Workbook();

            /* ** fill in workbook / worksheet content ** */

            // save workbook to MemoryStream
            var stream = new MemoryStream();
            wb.Save(stream, SaveFormat.Xlsx);
            stream.Position = 0;    // important!

            // add stream to response
            response.Content = new StreamContent(stream);

            // set Headers
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(dispositionType: "attachment"); // or "inline"
            response.Content.Headers.ContentDisposition.FileName = wb.FileName; // or other means of getting filename
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(mediaType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.Content.Headers.ContentLength = stream.Length;

            // set the success code
            response.StatusCode = HttpStatusCode.OK;
        }
        catch(Exception ex)
        {
            response.StatusCode = HttpStatusCode.InternalServerError;
            response.Content = null; // just in case
            response.ReasonPhrase = ex.Message;
        }

        return response;
    }

如果啟用了CORS,則可能需要允許Content-Disposition標頭:

    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(origins: "*", headers: "*", methods: "*");
        cors.ExposedHeaders.Add(item: "Content-Disposition");
        config.EnableCors(cors);

        /* The rest of WebAPI configuration */
    }

對於Javascript方面- 此處的答案可能會有所幫助。 (注意:確保將方法設置為POST,或將我的示例更改為GET。)

在ASP.NET中,可以通過以下代碼將XLS或XLSX文件發送到瀏覽器。

C#

//Save file and send to client browser using selected format
if (yourFileFormat == "XLS")
{
      workbook.Save(HttpContext.Current.Response, "output.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));

}
else
{
      workbook.Save(HttpContext.Current.Response, "output.xlsx", ContentDisposition.Attachment, new OoxmlSaveOptions(SaveFormat.Xlsx));
}

HttpContext.Current.Response.End();

上面的代碼會將XLS文件發送到瀏覽器。 如果您更改此行

if (yourFileFormat == "XLS")

if (yourFileFormat == "XLSX")

然后它將XLSX文件發送到瀏覽器。 請從下面的鏈接下載ASP.NET Web應用程序項目 ,以查看上面的代碼正在運行。

項目鏈接:

http://www.aspose.com/community/forums/293730/postattachment.aspx

請不要使用Workbook.SaveToStream()方法獲取內存流對象。 請檢查以下代碼,如何獲取不同格式的內存流對象,例如XLS,XLSX等。

//Create workbook object
Workbook wb = new Workbook("source.xlsx");

//This is how to save Workbook to XLS format
MemoryStream ms1 = new MemoryStream();
wb.Save(ms1, SaveFormat.Excel97To2003);

//Just to check if memory stream is good and contains XLS bytes
byte[] b1 = ms1.ToArray();
File.WriteAllBytes("output.xls", b1);

//This is how to save Workbook to XLSX format
MemoryStream ms2 = new MemoryStream();
wb.Save(ms2, SaveFormat.Xlsx);

//Just to check if memory stream is good and contains XLSX bytes
byte[] b2 = ms2.ToArray();
File.WriteAllBytes("output.xlsx", b2);

注意:我在Aspose擔任開發人員布道者

使用 .net 從使用File操作結果的 Andews 版本稍微調整。

[HttpGet("download")]
    public async Task<IActionResult> DownloadSystem()
    {
        var workbook = new Workbook();
        var fileName = $"Report.xlsx";
        var cd = new System.Net.Mime.ContentDisposition
        {
            FileName = fileName,
            Inline = false, 
        };
        Response.Headers.Add("Content-Disposition", cd.ToString());
        var stream = new MemoryStream();
        workbook.Save(stream, SaveFormat.Xlsx);
        stream.Position = 0;
        return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
    }

暫無
暫無

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

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