gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:01:58 26 4
gpt4 key购买 nike

我使用 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
}
}

我还有一个名为 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 header :

    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。)

关于javascript - Asp.net WebApi Aspose.Cells - 导出和下载 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37005750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com