Asp.net WebApi Aspose.Cells - 导出和下载excel

时间:2016-05-03 13:35:08

标签: javascript .net excel asp.net-web-api2 aspose-cells

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

实际上我正在尝试将xls文件保存在磁盘上,但我无法解决此问题。 这是我的get方法。

[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
        }
    }

我也有一个名为onClick的功能

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

当有人点击它时,应将文件保存在他的磁盘上(或打开浏览器,我可以选择地点和名称)。 怎么解决这个问题?

2 个答案:

答案 0 :(得分:1)

<强> 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端 - the answer here may help.(注意:请确保将方法设置为POST,或将我的示例更改为GET。)

答案 1 :(得分:0)

在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

担任开发人员传播者