从C#导出时,字符串未显示为CSV中的文本

本文关键字:显示 CSV 文本 字符串 | 更新日期: 2023-09-27 18:25:14

我有一组代码0075、0062等,在我的数据库中保存为字符串,并在我的模型中声明为字符串。但是,当我使用CSV Helper以CSV导出详细信息时,代码不会保存为文本,而是保存为数字。也就是说,0075被保存为75。我试过在字符串前面添加"=",但这不起作用。或者按以下方式尝试。但徒劳无功。以下是我的代码:

streamWriter.WriteLine("Code;");
streamWriter.WriteLine(string.Join(";", "'""+result.Code+"'""));

知道如何保存结果吗。在我的CSV中声明为字符串、文本的代码?

模型中声明的代码:

public string Code { get; set; }

从C#导出时,字符串未显示为CSV中的文本

看起来格式化逗号分隔的CSV以强制Excel将值解释为字符串所建议的方法有效(至少在Excel 2010上),即将每个单元格格式化为

"=""String Value"""

这里有一个静态助手类,它完成了必要的工作。由于您使用;作为分隔符,我认为您所在的区域,是十进制分隔符;为了概括我的答案,我使用System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator作为列表分隔符。

public static class CsvWriter
{
    public static void WriteToCsv(IEnumerable<string> cells, TextWriter writer, CultureInfo cultureInfo = null)
    {
        if (cells == null || writer == null)
            throw new ArgumentNullException();
        string listSeparator = (cultureInfo ?? System.Globalization.CultureInfo.CurrentCulture).TextInfo.ListSeparator;
        bool first = true;
        foreach (var cell in cells)
        {
            if (!first)
                writer.Write(listSeparator);
            writer.Write(ToCsvCell(cell));
            first = false;
        }
        writer.Write("'r'n");
    }
    public static void WriteToCsv<TEnumerable>(IEnumerable<TEnumerable> lines, TextWriter writer, CultureInfo cultureInfo = null) where TEnumerable : IEnumerable<string>
    {
        if (lines == null || writer == null)
            throw new ArgumentNullException();
        cultureInfo = cultureInfo ?? System.Globalization.CultureInfo.CurrentCulture;
        foreach (var cells in lines)
            WriteToCsv(cells, writer, cultureInfo);
    }
    public static string ToCsv<TEnumerable>(IEnumerable<TEnumerable> lines, CultureInfo cultureInfo = null) where TEnumerable : IEnumerable<string>
    {
        using (var writer = new StringWriter())
        {
            WriteToCsv(lines, writer, cultureInfo);
            return writer.ToString();
        }
    }
    static string ToCsvCell(string s)
    {
        if (s == null)
            return "";
        s = s.Replace("'"", "'"'"'"'"");
        return string.Format("'"='"'"{0}'"'"'"", s);
    }
}

然后,进行测试:

        var lines = new[] 
        {
            new [] { "0075", "0062", "abc", DateTime.Today.ToShortDateString() },
            new [] { "I said '"this is a quote'"" },
            new [] { "Embedded new line: 'r'nSecond Line",  string.Concat(Enumerable.Repeat(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator, 5).ToArray()) },
        };
        var path = Path.Combine(Path.GetTempPath(), "TestQuestion34034950.csv");
        using (var writer = new StreamWriter(path))
        {
            CsvWriter.WriteToCsv(lines, writer);
        }
        Console.WriteLine("Wrote " + path);

Excel将把上面创建的所有CSV单元格解释为字符串文字。