CSVHelper在Asp.Net MVC中的使用

1,从数据库读取数据,然后导出CSV文件

        [HttpPost]
        public FileResult ExportCSV()
        {
           
            var apps =。。。。//linq以及EF从数据库查询数据

            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            var csv = new CsvWriter(sw);
            foreach (var pp in apps)
            {
                csv.WriteField(0);      //set to '0'

                csv.WriteField("");     //set empty space

                csv.WriteField("haha");

                csv.NextRecord();
            }

            sw.Flush();

            ms.Position = 0;
            return File(ms, "text/comma-separated-values", "Export.csv");
        }    

 

2,页面上传CSV文件,服务器读取文件内容

@using (Html.BeginForm("ImportCSV", "ExportImport", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="row  row-margin">
        <div class="col-lg-4">
            <div class="form-group">
                <input type="file" name="csvToUpload" id="csvToUpload" accept=".csv">
            </div>
        </div>
        <div class="col-lg-6"></div>
        <div class="col-lg-2 pull-right">
            <button type="submit" class="btn btn-default btn-space-right btn-space-left"><span class="glyphicon glyphicon-import"></span> Import</button>
            <button type="button" class="btn btn-default pull-right" onclick="backHomePage();"><span class="glyphicon glyphicon-step-backward"></span> Quit</button>
        </div>
    </div>
}

 

        [HttpPost]
        public JsonResult ImportCSV(HttpPostedFileBase csvToUpload)
        {
                    using (var textReader = new StreamReader(csvToUpload.InputStream))
                    {
                        var csv = new CsvReader(textReader);

                        while (csv.Read())
                        {
                            var field = csv.GetField<string>(0);
                        }
                    }
                   
            .......
        }

 

 

参考:

CVSHELPER 使用指南

ASP.NET MVC 导出CSV文件

ASP.NET MVC:通过 FileResult 向 浏览器 发送文件

posted @ 2018-06-19 18:25  AlvinLiang  阅读(399)  评论(0编辑  收藏  举报