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 == ) 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();// 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(); } }
}

此例子中context最后为:

\Person Report\"\r\n\r\n\"Name\",\"Person Code\",\"Person Department\",\r\n\"a\" ,\"1\" ,\"Developer\" ,\r\n\"b\" ,\"2\" ,\"Test\" ,\r\n\"c\" ,\"3\" ,\"HR\" ,\r\n"

\r是回车,英文是Carriage return,表示使光标下移一格

\n是换行,英文是New line,表示使光标到行首

\r\n表示回车换行

3.4、定义csv文件格式

@using MvcDownLoadCsv.Extensions
@model List<MvcDownLoadCsv.Models.Person>
"Person Report"
@if (Model.Count == )
{<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 = "", Department = "Developer" },
new Person() { Name = "b", Code = "", Department = "Test" },
new Person() { Name = "c", Code = "", 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")[].submit();
}); $("#copyData").toggle(!!(document.body.createControlRange)).click(function (e) {
e.preventDefault();
try {
var range = document.body.createControlRange();
range.add($("#pis")[]);
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 > )
{
<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>

C#写csv文件的更多相关文章

  1. PLSQL_PLSQL读和写CSV文件方式(案例)

    2012-01-06 Created By BaoXinjin

  2. JavaCSV之写CSV文件

    与JavaCSV读CSV文件相对应,JavaCSV也可以用来写数据到CSV文件中. 1.准备工作 (1)第三方包库下载地址:https://sourceforge.net/projects/javac ...

  3. 【python】写csv文件时遇到的错误

    1.错误 在许多文件中,写入csv文件时都加"wb",w指写入,b指二进制 如: csvwrite=csv.writer(open("output.csv",& ...

  4. spark 写csv文件出现乱码 以及写文件读文件总结

    参考链接:https://blog.csdn.net/qq_56870570/article/details/118492373 result_with_newipad.write.mode(&quo ...

  5. python 写csv文件

    一.只有一列内容: def create_file(self, a, b): # 上传csv 文件 # os.remove('openfile.csv') open_file = open('5000 ...

  6. python笔记5-python2写csv文件中文乱码问题

    前言 python2最大的坑在于中文编码问题,遇到中文报错首先加u,再各种encode.decode. 当list.tuple.dict里面有中文时,打印出来的是Unicode编码,这个是无解的. 对 ...

  7. .NET 创建并写CSV文件

    /// <summary> /// 创建并写日志 /// </summary> /// <param name="SuccessA100">&l ...

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

    Python文档中有提到: open('eggs.csv', newline='') 也就是说,打开文件的时候多指定一个参数.Python文档中也有这样的示例: import csvwith open ...

  9. python写csv文件

    name=['lucy','jacky','eric','man','san'] place=['chongqing','guangzhou','beijing','shanghai','shenzh ...

随机推荐

  1. MY97 日期控件只输入今天之前的值

    <script type="text/javascript">                        function GetDate() {          ...

  2. [BZOJ1018][SHOI2008]堵塞的交通traffic 线段树维护连通性

    1018: [SHOI2008]堵塞的交通traffic Time Limit: 3 Sec  Memory Limit: 162 MB Submit: 3795  Solved: 1253 [Sub ...

  3. 找出数字数组中最大的元素(使用Math.max函数)

    从汤姆大叔的博客里看到了6个基础题目:本篇是第1题 - 找出数字数组中最大的元素(使用Match.max函数) 从要求上来看,不能将数组sort.不能遍历.只能使用Math.max,所以只能从java ...

  4. Java StringBuffer与StringBuider

    String 的值是不可变的,每次对String的操作都会生成新的String对象,不仅效率低,而且耗费大量内存空间. StringBuffer类和String类一样,也用来表示字符串,但是Strin ...

  5. Winform打砖块游戏制作step by step第一节---主界面搭建

    一 引子 为了让更多的编程初学者,轻松愉快地掌握面向对象的思考方法,对象继承和多态的妙用,故推出此系列随笔,还望大家多多支持. 二 本节内容---主界面搭建 1.主界面截图 2. 该窗体主要包含了以下 ...

  6. Delphi CRC32Verify控件

    unit CRC32Verify; interface uses  Windows, Messages, SysUtils, Classes, Forms; CONST    table:  ARRA ...

  7. Solr In Action 中文版 第一章(三)

    3.1              为什么选用Solr? 在本节中.我们希望能够提供一些关键信息来帮助于你推断Solr是否是贵公司技术方案的正确选择.我们先从Solr吸引软件架构师的方面说起. 3.1  ...

  8. net.sf.json.JSONException: There is a cycle in the hierarchy!错误解决方案

    net.sf.json.JSONException: There is a cycle in the hierarchy!错误解决方案 今天在用List集合转换成json数组的时候发生了这个错误,这个 ...

  9. 用new和delete运算符进行动态分配和撤销存储空间

    測试描写叙述:暂时开辟一个存储空间以存放一个结构体数据 #include <iostream> #include <string> using namespace std; s ...

  10. 【Hadoop】三句话告诉你 mapreduce 中MAP进程的数量怎么控制?

    1.果断先上结论 1.如果想增加map个数,则设置mapred.map.tasks 为一个较大的值. 2.如果想减小map个数,则设置mapred.min.split.size 为一个较大的值. 3. ...