我有一个使用 Microsoft.Office.Interop.Excel 的工作簿。我的问题是这将是一个 API 调用,目前它可以工作但会保存到服务器。有没有办法让它直接下载到客户端并避免服务器端保存。我为 csv 使用了内存流,但这不支持我需要的东西,现在需要使用 excel。
Workbook workbook = new Application().Workbooks.Add();
var mySheet = (Worksheet)workbook.Worksheets[1];
var lastRow = mySheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell).Row;
foreach (var tempResult in violationsResults)
{
lastRow += 1;
mySheet.Cells[lastRow, 01] = tempResult.InfractionDate;
mySheet.Cells[lastRow, 02] = tempResult.ProductName;
mySheet.Cells[lastRow, 03] = tempResult.Sku;
mySheet.Cells[lastRow, 04] = tempResult.ProductLine;
mySheet.Cells[lastRow, 05] = tempResult.MappPrice;
mySheet.Cells[lastRow, 06] = tempResult.AdvertisedPrice;
mySheet.Cells[lastRow, 07] = tempResult.Difference;
mySheet.Cells[lastRow, 08] = tempResult.SellerDomain;
mySheet.Cells[lastRow, 09] = tempResult.Merchant;
mySheet.Cells[lastRow, 10] = tempResult.Upc;
mySheet.Cells[lastRow, 11] = tempResult.DomainSku;
mySheet.Cells[lastRow, 12] = tempResult.Fba;
mySheet.Cells[lastRow, 13] = tempResult.Mvid;
}
workbook.SaveAs("C:\\Temp\\hello_excel.xlsx");
从您的临时文件夹中获取一个文件并进行下载,或者使用 MemoryStream 存储您的文件然后下载。
public void DownloadWorkbook(string filePath)
{
FileInfo file = new FileInfo(filePath);
HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
response.AddHeader("Content-Length", file.Length.ToString());
response.ContentType = "text/csv";
response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
response.TransmitFile(file.FullName);
response.End();
}
希望能帮助到你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句