【问题标题】:Write CSV then Save or Edit写入 CSV,然后保存或编辑
【发布时间】:2018-02-28 13:56:24
【问题描述】:

我有问题。我在运行时创建一个 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);
    }

【问题讨论】:

  • 打开导航调试器,查看响应内容,您可能会得到更多信息。
  • 在调用 'send()' 方法时由 'XMLHttpRequest' 启动的下载 此下载发生在文档处理期间。进入响应正文:UTI 代码、交易对手、成熟度、交易量、评估日期 ecc ecc ecc
  • 通过直接写入响应流来节省 RAM 并开始更快地将结果推送给用户,而不是 StringBuilder。
  • 还有:WriteHeader() 长什么样子?
  • 不要滚动你自己的 CSV 编写逻辑。你在重新发明轮子。您将拥有不遵守 CSV 文件规则的凌乱代码。相反,请使用为您解决这些问题的库,例如 CsvHelper

标签: c# csv


【解决方案1】:

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

filename 是否包含文件扩展名?

如果不行,试试这个

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

【讨论】:

    【解决方案2】:

    我仍然不明白问题可能出在哪里,我尝试了不同的解决方案,然后我在网上找到了一个通过演示工作的示例,但是一旦我实施它,它就不起作用了,可能是我使用 sharepoint 2013 并且引用导出的按钮位于 webpart 中?

    代码:

    HttpResponse Response = HttpContext.Current.Response;
    
    string csv = string.Empty;
    csv += "UTI code, Counterparty, Maturity, Volume, Evaluation Date";
    csv += "\r\n";
    
    string _uti, _counterparty;
    DateTime _maturity, _date;
    decimal _volume;
    
    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;
                csv += _uti + ",";
                csv += _counterparty + ",";
                csv += _maturity + ",";
                csv += _volume + ",";
                csv += _date;
                csv += "\r\n";
            }
    
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
            Response.Charset = "";
            Response.ContentType = "application/text";
            Response.Output.Write(csv);
            Response.Flush();
            Response.End();
    

    【讨论】:

      【解决方案3】:

      这应该会有所帮助:

      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);
          }
      
      
          MemoryStream mstream = new MemoryStream();
          StreamWriter sw = new StreamWriter(mstream);
          sw.Write(csv);
          sw.Flush();
          sw.Close();
          byte[] byteArray = mstream.ToArray();
          mstream.Flush();
          mstream.Close();
          HttpContext.Current.Response.BinaryWrite(byteArray);
          HttpContext.Current.Response.End();
      }
      

      【讨论】:

      • 请充实你的答案。请不要只提供代码。向用户解释。教他们需要做什么的原则。
      • 代码是不言自明的,我改变了将数据写入Response的方式,而不是使用Response.Write我使用MemoryStream,将内容加载到byte[]数组并将所有内容写为二进制
      • @AMINCHAR 巨大的代码转储与自我解释相反。始终解释您所做的更改以及更改的原因。
      猜你喜欢
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多