我创建了一个操作,使用officeopenxml
以下是我将表格转换为Excel的方法:
public ActionResult ExportToExcel()
{
_lstRecords = (List<Summary>) Session["Paging"];
List<Excel> lstExportedExcel = new List<Excel>();
foreach (var item in _lstRecords)
{
Excel export = new Excel();
export.Date = item.Date.ToString("MM/dd/yyyy HH:mm");
export.Assignment = item.codeAssignment.Assignment;
export.County = item.codeCounty.County;
lstExportedExcel.Add(export);
}
ExcelPackage excel = new ExcelPackage();
var color = ColorTranslator.FromHtml("#2c3e50");
var border = ExcelBorderStyle.Double;
var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
workSheet.Cells[1, 1].LoadFromCollection(lstExportedExcel.OrderBy(x => x.Date).ToList(), true);
workSheet.DefaultColWidth = 25.0;
workSheet.Cells[1,1,1,10].Style.Border.BorderAround(border, color);
workSheet.Cells[1, 1, 1, 10].Style.Font.Bold = true;
workSheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
workSheet.InsertRow(2,1);
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=SummaryRecords.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
return RedirectToAction("Index");
}
现在,当用户点击视图上的按钮时,他们会在幕后采取此操作,并出现一个对话框,要求他们打开或保存..
现在我的下一个目标是能够直接从我的应用程序添加此Excel工作表作为电子邮件的附件。因此,我想在我的视图中添加另一个按钮,该按钮将打开Outlook,将此excel表作为附件,无需保存文档..这是可能的,还是用户必须下载文档?