rai*_*orn 1 c# filestreamresult asp.net-mvc-4
我需要构建一个方法,它将接收模型,从中构建excel(构建和接收部分完成没有问题),然后使用内存流导出(让用户下载它)(不将其保存在服务器上).我是ASP.NET和MVC的新手,所以我找到了指南并将其构建为一个教程项目:
public FileResult Download()
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "1";
xlWorkSheet.Cells[2, 2] = "One";
xlWorkSheet.Cells[3, 1] = "2";
xlWorkSheet.Cells[3, 2] = "Two";
var path = "C:\\Work-Work\\TestFolder\\XCLbuildTry1\\csharp-Excel.xls";
xlWorkBook.SaveAs(path);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
return File(path, "application/vnd.ms-excel", "WidgetData.xlsx");
}
Run Code Online (Sandbox Code Playgroud)
现在我需要更改此代码以使此方法发送我的excel文件而不保存我的excel文件在服务器上.我试图在堆栈上谷歌一些指南和答案,但现在我无法找到一个解决方案,我可以实现.
我想我应该使用FileStreamResult,但所有指南都没有提供有关创建和插入文件的特定信息.
不幸的是,Microsoft.Office.Interop.Excel.Workbook接口(msdn)似乎不允许您将工作簿转换为内存流.
然而,在过去,我使用了一个外部库,EPPlus,它曾经非常有效.
请参阅下面的使用EPPlus的代码,它不需要您将文件保存在服务器上.
商业逻辑
public MemoryStream Download() {
MemoryStream memStream;
using (var package = new ExcelPackage()) {
var worksheet = package.Workbook.Worksheets.Add("New Sheet");
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[2, 1].Value = "1";
worksheet.Cells[2, 2].Value = "One";
worksheet.Cells[3, 1].Value = "2";
worksheet.Cells[3, 2].Value = "Two";
memStream = new MemoryStream(package.GetAsByteArray());
}
return memStream;
}
Run Code Online (Sandbox Code Playgroud)
调节器
public FileStreamResult Download() {
var memStream = BusinessLogic.Download();
result File(memStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12086 次 |
| 最近记录: |