MiniExcel导入与导出

文章描述了如何使用C#通过API实现Excel文件的导入(读取并显示数据)、导出静态数据以及从模板下载生成Excel文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   public class Person
    {
        [ExcelColumnName("姓名")]
        public string? Name { get; set; }
        [ExcelColumnName("性别")]
        public string? Sex { get; set; }
        [ExcelColumnName("年龄")]
        public string? Age { get; set; }
    }
        [HttpPost("import")]
        public IActionResult ImportExcel(IFormFile excel)
        {
            //内存流
            var stream = new MemoryStream();
            //将excel文件复制到内存流
            excel.CopyTo(stream);
            //在内存中查询Person并转换为集合
            var list =  stream.Query<Person>().ToList();
            foreach (var person in list) 
            {
                Console.WriteLine(person.Name);
                Console.WriteLine(person.Sex);
                Console.WriteLine(person.Age);
            }
            return Ok("File import successfully");
        }
        [HttpGet("export")]
        public IActionResult ExportExcel()
        {
            //values 是导出的数据
            var values = new[] 
            {
                new { Column1 = "MiniExcel", Column2 = 1 },
                new { Column1 = "Github", Column2 = 2}
            };
            //内存流
            var memoryStream = new MemoryStream();
            //将数据保存到内存流
            memoryStream.SaveAs(values);
            //设置流中的读取位置
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "demo.xlsx"
            };
        }
       [HttpPost("downloadExcelTemplate")]
        public IActionResult DownloadExcelFromTemplatePath()
        {
            //模板物理路径
            string templatePath = "excelTemplate.xlsx";
            Dictionary<string, object> value = new Dictionary<string, object>()
            {
               
            };
            MemoryStream memoryStream = new MemoryStream();
            memoryStream.SaveAsByTemplate(templatePath, value);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "demo.xlsx"
            };
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值