将 Excel 包下载为文件而不创建物理文件?
Download Excel package as file without creating a physical file?
我正在寻找将文件下载到客户端 pc 的代码,我不想存储物理文件并担心在以后删除它。
目前我创建了一个物理文件然后下载它,文件名保持不变,所以它取代了以前的文件。我担心的是,当多个用户同时尝试下载时,他们可能最终会覆盖文件。
这是我的一些代码:
using (var package = new ExcelPackage(existingFile))
{
// edit cells and add details into the excel file
//Here u save the file, i would like this to be a stream
using (FileStream aFile = new FileStream(MapPath("../../template/LeadsExport.xlsx"), FileMode.Create))
{
try
{
package.SaveAs(aFile);
aFile.Close();
}
catch (Exception ex)
{
}
}
// Here i download the file, i would like this to use a stream and not a physical file
FileInfo file = new FileInfo(MapPath("../../template/LeadsExport.xlsx"));
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
}
我想将包保存到文件流中而不是物理文件中,然后通过某种方式下载它。
在代码和问题文本本身中,您已经有了一半的答案。不要将 Excel 包写入磁盘,而是将其写入响应流。
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=LeadsExport.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
我正在寻找将文件下载到客户端 pc 的代码,我不想存储物理文件并担心在以后删除它。 目前我创建了一个物理文件然后下载它,文件名保持不变,所以它取代了以前的文件。我担心的是,当多个用户同时尝试下载时,他们可能最终会覆盖文件。
这是我的一些代码:
using (var package = new ExcelPackage(existingFile))
{
// edit cells and add details into the excel file
//Here u save the file, i would like this to be a stream
using (FileStream aFile = new FileStream(MapPath("../../template/LeadsExport.xlsx"), FileMode.Create))
{
try
{
package.SaveAs(aFile);
aFile.Close();
}
catch (Exception ex)
{
}
}
// Here i download the file, i would like this to use a stream and not a physical file
FileInfo file = new FileInfo(MapPath("../../template/LeadsExport.xlsx"));
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
}
我想将包保存到文件流中而不是物理文件中,然后通过某种方式下载它。
在代码和问题文本本身中,您已经有了一半的答案。不要将 Excel 包写入磁盘,而是将其写入响应流。
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=LeadsExport.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(package.GetAsByteArray());
Response.End();