欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET MVC 导出CSV 的 CsvFileResult 类

程序员文章站 2023-08-23 11:20:20
public class csvfileresult : fileresult where t : class { private ienumerable _data;...
public class csvfileresult : fileresult where t : class
    {
        private ienumerable _data;


        public csvfileresult(ienumerable data)
            : base("text/csv")
        {
            _data = data;
        }


        protected override void writefile(httpresponsebase response)
        {
            var maxline = int.parse(configurationmanager.appsettings["csvexport:maxline"]);


            int count = 0;
            var outputstream = response.outputstream;
            using (var streamwriter = new streamwriter(outputstream, system.text.encoding.utf8))
            using (var writer = new csvwriter(streamwriter))
            {
                writer.writeheader();
                foreach (var item in _data)
                {
                    writer.writerecord(item);
                    count++;
                    if (count % 50 == 0)
                    {
                        streamwriter.flush();
                        response.flush();
                    }
                    if (count >= maxline)
                    {
                        break;
                    }
                }
            }
        }
    }






实现依赖于csvhelper

ASP.NET MVC 导出CSV 的 CsvFileResult 类