在 Asp.Net Core 2.2 中写入以制表符分隔的文本文件

Write Text file with tab-delimited in Asp.Net Core 2.2

您好,您有任何指南、工作帮助或分步说明如何导出为制表符分隔的文本。我正在使用 Asp.Net Core 2.2 MVC EF。我想从我的 table 中导出一个列表。我想要一个按钮,用户点击此 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; 
        }

您需要使用 Configuration.

设置 CsvWriter

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

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

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

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

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