.net mvc导出execl控制器视图全过程
时间: 2023-05-24 08:01:23 浏览: 68
对于 .net mvc 导出 Excel 控制器视图全过程,可以分为以下几个步骤:
1. 创建 Excel 文件以及工作表
2. 将数据填入 Excel 工作表中
3. 保存 Excel 文件并导出
具体实现可以参考以下代码:
//引入命名空间
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using NPOI.HSSF.UserModel;//注意这里的引用
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
public class ExcelController : Controller
{
//导出Excel
public ActionResult ExportExcel()
{
//模拟数据
List<Model> dataList = new List<Model>();
dataList.Add(new Model { Id = 1, Name = "张三", Age = 20 });
dataList.Add(new Model { Id = 2, Name = "李四", Age = 25 });
dataList.Add(new Model { Id = 3, Name = "王五", Age = 30 });
//创建Excel文件以及工作表
IWorkbook workbook;
string filePath = Server.MapPath("~/ExportExcel/");
string fileName = "test.xlsx";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
if (System.IO.File.Exists(filePath + fileName))
{
System.IO.File.Delete(filePath + fileName);
}
//创建新的Excel文档
workbook = new XSSFWorkbook();
//创建新的工作表
ISheet sheet = workbook.CreateSheet("Sheet1");
//创建标题行
IRow row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue("编号");
row.CreateCell(1).SetCellValue("姓名");
row.CreateCell(2).SetCellValue("年龄");
//将数据填入Excel工作表中
for (int i = 0; i < dataList.Count; i++)
{
IRow newRow = sheet.CreateRow(i + 1);
newRow.CreateCell(0).SetCellValue(dataList[i].Id.ToString());
newRow.CreateCell(1).SetCellValue(dataList[i].Name);
newRow.CreateCell(2).SetCellValue(dataList[i].Age.ToString());
}
//保存Excel文件并导出
FileStream outFile = new FileStream(filePath + fileName, FileMode.Create, FileAccess.Write);
workbook.Write(outFile);
outFile.Close();
return File(filePath + fileName, "application/vnd.ms-excel", "test.xlsx");
}
}
注意,这里使用了 NPOI 这个第三方库来帮助处理 Excel 文件。要使用此库,你需要先安装它并引用它的命名空间。
至于 ".lua closure factory 完整代码" 和 "中文加密" 的问题,也属于编程类问题,可以回答。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)