今天在寫一個將資料下載成 Excel 的檔案的 API 時,遇到怎麼下載檔案大小都是 0,且無法開啟的問題。後來發現是因為使用了 MemoryStream 來寫資料,寫完之後它的位置在最後面。因此後來傳給 HttpMessageResponse 的 HttpContent 時,從最後面讀取,因此檔案大小都是 0. 所以加上了一段,把 position 設定回 0 的邏輯才解決這個問題。 public Stream GetReportStream(Report report) { var memoryStream = new MemoryStream(); using (var workbook = new XLWorkbook()) { workbook.AddWorksheet(report.Details, "Details"); workbook.AddWorksheet(report.Summary, "Summary"); workbook.SaveAs(memoryStream); memoryStream.Position = 0; } return memoryStream; } private static HttpResponseMessage HttpExcelFile(Stream excel, string fileName) { var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(excel) }; result.Con...