C#写csv文件

1、在项目中经常需要把报表下载为csv格式的文件,如何在C#中写csv文件,以下为一个简化的例子,不使用任何控件,旨在说明用法。

前端view

下载结果

2、创建一个MVC项目(Intranet Application),项目结构如下

3、各部分代码:

3.1、定义实体

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcDownLoadCsv.Models
{
    public class Person
    {
        public string Name { get; set; }
        public string Code { get; set; }
        public string Department { get; set; }
    }
}

3.2、定义共用方法,将object数据转换为HtmlString,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcDownLoadCsv.Extensions
{
    public static class DataTypeExtensions
    {
        public static HtmlString ToHtmlCsv(this object o)
        {
            if (o == null) return new HtmlString("");

            var s = o.ToString();

            if (s.Length == 0) return new HtmlString(s);

            s = s.Replace("\"", "\"\"");
            HtmlString hs = new HtmlString(s.ToString());

            return new HtmlString(string.Concat("\"", s, "\""));

        }

    }
}

3.3、定义公用方法,把Model数据转换为csv格式文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace MvcDownLoadCsv
{
    public class CsvDownloadResult : ActionResult
    {

        public CsvDownloadResult(string name, object model)
        {

            this.name = name;
            this.model = model;

        }

        private string name;
        private object model;

        public override void ExecuteResult(ControllerContext context)
        {

            context.HttpContext.Response.Clear();
            context.HttpContext.Response.AddHeader("content-disposition", string.Format("attachment; filename=My.{0}.csv", name));
            context.HttpContext.Response.ContentEncoding = Encoding.GetEncoding(1252);// Use ANSI encoding
            context.HttpContext.Response.ContentType = "application/vnd.ms-excel";

            var csv = "";

            using (StringWriter sw = new StringWriter())
            {

                var viewResult = ViewEngines.Engines.FindPartialView(context, name + "Csv");
                var viewContext = new ViewContext(context, viewResult.View, new ViewDataDictionary(model), new TempDataDictionary(), sw);
                viewResult.View.Render(viewContext, sw);

                csv = sw.GetStringBuilder().ToString();

                csv = Regex.Replace(csv, "\r\n[ ]+\r\n[ ]+", "\r\n");
                csv = Regex.Replace(csv, ",\r\n[ ]*", ",");

            }

            context.HttpContext.Response.Write(csv);

            context.HttpContext.Response.End();

        }

    }
}

3.4、定义csv文件格式

@using MvcDownLoadCsv.Extensions
@model List<MvcDownLoadCsv.Models.Person>
"Person Report"
@if (Model.Count == 0)
{<text>"No Person find."</text>
}
else
{<text>
"Name",
"Person Code",
"Person Department",
</text>

    foreach (var item in Model)
    {

        @item.Name.ToHtmlCsv() <text>,</text>
        @item.Code.ToHtmlCsv() <text>,</text>
        @item.Department.ToHtmlCsv() <text>,</text>
        <text></text>
    }
}

3.5、后台方法,构造数据,定义响应前端下载的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcDownLoadCsv.Models;

namespace MvcDownLoadCsv.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View(GetPerson());
        }

        public ActionResult About()
        {
            return View();
        }

        public List<Person> GetPerson()
        {
            List<Person> lst = new List<Person>()
            {
                new Person() { Name = "a", Code = "1", Department = "Developer" },
                new Person() { Name = "b", Code = "2", Department = "Test" },
                new Person() { Name = "c", Code = "3", Department = "HR" }
            };
            return lst;
        }

        [HttpPost]
        public ActionResult DownloadCsv()
        {
            //Person为定义报表格式的cshtml文件名称, GetPerson()返回的是报表数据
            return new CsvDownloadResult("Person", GetPerson());
        }

    }

}

3.6、前端页面view

@model List<MvcDownLoadCsv.Models.Person>
@{
    ViewBag.Title = "Home Page";
}
    <script type="text/javascript">

        $(document).ready(function () {
            $("#downloadData").click(function (e) {
                e.preventDefault();
                $("#downloadCriteria")[0].submit();
            });

            $("#copyData").toggle(!!(document.body.createControlRange)).click(function (e) {
                e.preventDefault();
                try {
                    var range = document.body.createControlRange();
                    range.add($("#pis")[0]);
                    range.execCommand("Copy");
                    alert("Report data was copied to the clipboard.");
                }
                catch (e) { alert("Failed to copy the report data to the clipboard:\n\n" + e.message); }
            });
        });
    </script>

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

 <div  style="height:30px" class="actions">
        @if (Model.Count > 0)
        {
            <a href="javascript:void(0);" id="downloadData" class="action" title="Download Data to Excel">download</a>
            <a href="" id="copyData" class="action" title="Copy Results to Clipboard">copy</a>
            <a href="" id="downloadDataForPopup" class="action" title="Download Data to Excel" style="display:none">downloadForPopup</a>
        }
 </div>

 <div class="fieldset">
    <form action="@Url.Action("DownloadCsv", "Home")" method="post" id="downloadCriteria">

    </form>
<table id="projects" class="data">
    <tr>
        <th>Name</th>
        <th>Code</th>
        <th>Department</th>
    </tr>
    @{

        foreach (var item in Model)
        {
        <tr>
            <td>@item.Name</td>
            <td>@item.Code</td>
            <td>@item.Department</td>
        </tr>
        }
    }
</table>
</div>

时间: 2024-10-06 22:01:26

C#写csv文件的相关文章

写csv文件时遇到的错误

1.错误 在许多文件中,写入csv文件时都加"wb",w指写入,b指二进制 如: csvwrite=csv.writer(open("output.csv","wb")) Temp=["row1","row2","row3",] csvwrite.writerow(Temp) 或者是 #!/usr/bin/env python #coding:utf-8 import csv #csv写

JavaCSV之写CSV文件

与JavaCSV读CSV文件相对应,JavaCSV也可以用来写数据到CSV文件中. 1.准备工作 (1)第三方包库下载地址:https://sourceforge.net/projects/javacsv (2)相关文档:http://javacsv.sourceforge.net/ 2.使用简单的读操作 (1)引入javacsv包相应的类 import com.csvreader.CsvWriter; (2)创建文件路径 String file = "src/com/xiaoming/csv/

python 写csv文件

一.只有一列内容: def create_file(self, a, b): # 上传csv 文件 # os.remove('openfile.csv') open_file = open('50000file.csv', 'w+') open_file.write('商户ID'+','+'类目'+','+'描述'+','+'变更分值'+ '\n') for i in range(a, b): open_file.write(str(i)+','+'商户食品安全-重大食品安全事件'+','+'因

.NET 创建并写CSV文件

/// <summary> /// 创建并写日志 /// </summary> /// <param name="SuccessA100"></param> /// <param name="Result"></param> public void WriteLog(List<string> SuccessA100,string Result,string A102) { if (S

python3 写CSV文件多一个空行的解决办法

Python文档中有提到: open('eggs.csv', newline='') 也就是说,打开文件的时候多指定一个参数.Python文档中也有这样的示例: import csvwith open('eggs.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writero

java写CSV文件

1.首先pom.xml引入依赖 <dependency>   <groupId>com.opencsv</groupId>   <artifactId>opencsv</artifactId>   <version>3.10</version></dependency> 2.要输出的实体T字段加上注解 @CsvBindByName(column = "标题名") 3.实现方法,dataLis

.NET 泛型集合数据写CSV文件

1.功能类 using System;using System.Collections.Generic;using System.ComponentModel;using System.IO;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks; namespace Infrastructure{    public static class FileExtensions 

用C#写的读写CSV文件

用C#写的读取CSV文件的源代码 CSV文件的格子中包含逗号,引号,换行等,都能轻松读取,而且可以把数据转化成DATATABLE格式 using System; using System.Text; using System.Collections; using System.IO; using System.Data; using System.Text.RegularExpressions; using System.Diagnostics; namespace CsvLib { #regi

PHP导出CSV文件

转载:http://blog.csdn.net/huyanping/article/details/7068356 经常会碰到需要从数据库中导出数据到Excel文件,用一些开源的类库,比如PHPExcel,确实比较容易实现,但对大量数据的支持很不好,很容易到达PHP内存使用上限.这里的方法是利用fputcsv写CSV文件的方法,直接向浏览器输出Excel文件. // 输出Excel文件头,可把user.csv换成你要的文件名 header('Content-Type: application/v