[英]How to Export an Excel File using C#
Helo,我已經在谷歌和這里 (StackOverflow) 上搜索過,但我沒有完成任何解決方案。
我的文件夾中有一個 Excel 文件,我需要在我的控制器上創建一個方法來下載這個文件。
在我的 React 網站中,我需要將此文件發送到用戶計算機。
我嘗試使用 ActionResult、FileStreamResult、HttpResponseMessage 和其他,使用 File.ReadAllbytes 從文件夾中讀取文件,將 Header 放在響應中。
在決賽我得到了這個。
{ FileContents: "allcontentoffilehere....", Contenttype: "application/octet-stream", FileDownloadName: "filename.xls"}
並使用此 JavaScript 下載:
var bytes = new Uint8Array(responseDownloadFile.data.FileContents);
var blob = new Blob([bytes], {
type: responseDownloadFile.data.ContentType
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = responseDownloadFile.data.FileDownloadName;
document.body.appendChild(link);
link.click();
但下載時文件已損壞。
任何人都可以幫助我嗎?
嘗試在您的 API 上返回 HttpResponseMessage 類型
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent([file bytes]);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/file type");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "filename.xlsx"
};
return result;
並在您的前端執行代碼:
window.location.href = "link to your api endpoint to download excel";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.