【问题标题】:Write Text file with tab-delimited in Asp.Net Core 2.2在 Asp.Net Core 2.2 中写入制表符分隔的文本文件
【发布时间】:2020-02-08 14:01:30
【问题描述】:

您好,您有任何指南、工作帮助或逐步导出到制表符分隔的文本的方法吗?我正在使用 Asp.Net Core 2.2 MVC EF。我想从我的表中导出一个列表。我想要一个按钮,用户在此 DownloadFile 操作中单击将触发该按钮。

public IActionResult DownloadFile()
        {
            var payments = new List<BdoPE>
            {
                new BdoPE
                {
                    DocDateInDoc = "01/01/2019",
                    DocType = "DZ",
                    CompanyCode = "3000",
                    PosDateInDoc = "01/01/2019",
                    FiscalPeriod = "01",
                    CurrentKey = "PHP",
                    RefDocNum = "Over-The-Counter",
                    DocHeadT = "BDO",
                    PosKeyInNextLine = "40",
                    AccMatNextLine = "11231131",
                    AmountDocCur = "0000000010050",
                    ValDate = "01/01/2019",
                    AssignNum = "EEA",
                    ItemText = "1000136212  ",
                    PosKeyInNextLine2 = "15",
                    AccMatNextLine2 = "0115027FF",
                    AmountDocCur2 = "0000000010050",
                    BaseDateDueCal = "01/01/2019",
                    ItemText2 = "1000136212"
                },
            };

            // I want this part to let the user select where they want to save the text file.
            using (var writer = new StreamWriter("path\\to\\file.txt")) // not static location like this one.

            using (var csv = new CsvWriter(writer))
            {
                csv.WriteHeader<BdoPE>();
                csv.WriteRecord(payments);
            }

            // where should i put the delimiter part?

            return; 
        }

【问题讨论】:

  • CsvWriter 类从何而来?
  • 我正在使用来自此页面的 CsvHelper joshclose.github.io/CsvHelper
  • 文档很清楚。您需要 CsvWriter(TextWriter, Configuration) 构造函数,并且 Configuration 对象具有可以设置的 Delimiter 属性。
  • 对不起,我只是 .Net core 的新手,我仍然很难。
  • 嗯,你的问题已经足够得到下一个提示了,所以你们都很好:)

标签: c# entity-framework-core text-files asp.net-core-2.2 asp.net-core-mvc-2.0


【解决方案1】:

您需要使用 Configuration 设置 CsvWriter。

因此,您的代码只需稍作改动:

[...]
var configuration = new CsvHelper.Configuration.Configuration();
configuration.Delimiter = '\t';

using (var csv = new CsvWriter(writer, configuration))
{
    csv.WriteHeader<BdoPE>();
    csv.WriteRecord(payments);
}
[...]

【讨论】:

    【解决方案2】:

    我使用下面的代码使用 CsvHelper 设置分隔符。

     var config = new CsvConfiguration(CultureInfo.CurrentCulture)
     {
          Delimiter = "\t"
     };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2016-01-02
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      相关资源
      最近更新 更多