第三种方式呢,就是借用第三方插件 NPOI 来实现Execl 导出
第一步:在NuGut包中下载NPOI 组件
第二步:编辑控制器代码
public FileResult ExcelNewKeyPromotion()
{
string title = "Market Sensing-Key Promotion"; var model = GetList(); NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1"); IFont font = book.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;//加粗 IFont font1 = book.CreateFont();
font1.FontHeightInPoints = ;
font1.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;//加粗 NPOI.SS.UserModel.IRow row0 = sheet1.CreateRow();
SetCellRangeAddress(sheet1, , , , ); //设置夸单元格
ICellStyle cellstyle = book.CreateCellStyle();//设置垂直居中格式
cellstyle.Alignment = HorizontalAlignment.Center; //设置水平居中
cellstyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
cellstyle.SetFont(font); //设置字体
ICell cell = row0.CreateCell();
cell.CellStyle = cellstyle;
cell.SetCellValue(title); NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(); ICellStyle Rowstyle = book.CreateCellStyle();//设置垂直居中格式
Rowstyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
Rowstyle.Alignment = HorizontalAlignment.Center; //设置水平居中
Rowstyle.FillPattern = FillPattern.SolidForeground;
Rowstyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index; //设置背景色
Rowstyle.SetFont(font1);
var lstTitle = new List<string> { "Year", "Week", "Date"};
for (int i = ; i < lstTitle.Count(); i++)
{
ICell cellRow1 = row1.CreateCell(i);
cellRow1.CellStyle = Rowstyle;
cellRow1.SetCellValue(lstTitle[i]);
} // row1.CreateCell(12).SetCellValue("Photo");
ICell cellRow2 = row1.CreateCell();
cellRow2.CellStyle = Rowstyle;
cellRow2.SetCellValue("Photo");
Rowstyle.SetFont(font1);
SetCellRangeAddress(sheet1, , , , ); //设置夸单元格 int rowIndex = ;
for (int i = ; i < model.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + ); rowtemp.Height = ; //设置行高 rowtemp.CreateCell().SetCellValue(model[i].Id.ToString());
rowtemp.CreateCell().SetCellValue(model[i].Name.ToString());
rowtemp.CreateCell().SetCellValue(model[i].CreateTime.ToString("yyyy-MM-dd hh:mm:ss")); rowIndex++;
} System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
ms.Seek(, SeekOrigin.Begin); string fileName = "Market Sensing / KeyPromotion.xls";
return File(ms, "application/vnd.ms-excel", fileName); }
第三步:前端页面
function ExcelNewKeyPromotion() { window.open("/Home/ExcelNewKeyPromotion")
}