c# - 写入 CSV 然后保存或编辑

标签 c# csv

我有一个问题。我在运行时创建一个 CSV,然后让用户能够保存或打开它,但它对我没有任何作用,我做错了什么?有人可以帮助我吗?

public void WriteToCSV(List<mifid2_vpc_monitored_detail_view> list, string filename)
    {
        string attachment = "attachment; filename=" + filename;

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;


        WriteHeader();
        StringBuilder csv = new StringBuilder();

        string _uti, _counterparty;
        DateTime _maturity, _date;
        decimal _volume;

        var newLine = "";

        for (int i = 0; i < list.Count; i++)
        {
            if (list[i].uti_cd == null) _uti = "-"; else _uti = list[i].uti_cd;
            if (list[i].namecounterparty == null) _counterparty = "-"; else _counterparty = list[i].namecounterparty;
            if (list[i].maturity == null) _maturity = DateTime.MinValue.Date; else _maturity = list[i].maturity;
            if (list[i].contract_volume == 0) _volume = 0; else _volume = list[i].contract_volume;
            if (list[i].evaluation_date == null) _date = DateTime.MinValue.Date; else _date = list[i].evaluation_date;

            newLine = string.Format("{0},{1},{2},{3},{4}", _uti, _counterparty, _maturity, _volume, _date);
            csv.AppendLine(newLine);
        }

        HttpContext.Current.Response.Write(csv.ToString());
        HttpContext.Current.Response.End();
    }

    private void WriteHeader()
    {
        string columnNames = "UTI code, Counterparty, Maturity, Volume, Evaluation Date";
        HttpContext.Current.Response.Write(columnNames);
        HttpContext.Current.Response.Write(Environment.NewLine);
    }

最佳答案

代码对我来说工作得很好。但是浏览器下载没有扩展名的文件。

filename 是否包含文件扩展名?

如果没有,试试这个

string attachment = "attachment; filename=" + filename + ".csv";

关于c# - 写入 CSV 然后保存或编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49031241/

相关文章:

c# - 使用额外变量的 Linq 多重连接条件

c# - 无法连接到仅使用临时密码套件的 SSL 服务器(无法联系本地安全机构)

c# - 有没有办法检查 MSMQ 队列中有多少消息?

python - 提取csv文件的多个多边形坐标

Python Numpy 无法将 CSV 文件中的字符串转换为整数

python - 从 csv [标题 + 内容] 中删除重复行

c# - 通用工作计划。将文件从 FileOpenPicker 复制到本地存储

c# - 将 wp8 升级到 wp8.1 silverlight,无法启动调试器

iphone - 如何在xcode中从excel加载数据?

python - Scrapy 已完成运行,结果显示在控制台中,但 CSV 输出仍为空白