質問

I am using the CsvHelper library to read/write csv files from my .net code.

All functionality are working fine so far, yet I am stuck in how can I keep the leading zeros when writing to csv file using the CsvWriter Class? Currently, the string values such as "020" or "001" get printed on the csv file as "20" and "1"

役に立ちましたか?

解決

This is a known problem, with a known solution, described here:

The solution is to write a number in this format:

="001"

These don't work (tested in 2010) - leading zeros are trimmed: 001, "001", =001

他のヒント

After checking the comments on my question, I have found out that the leading zeros are actually stored within the CSV file. What made the confusion is when opening the file on Excel, it automatically formatted the numeric fields, trimming the leading zeros, so it showed as "20" and "1" instead of 020 and 001.

CsvHelper no longer includes Excel-related features within the base library.

If you're not using quotes, a simple trick to include the equals (=) symbol when writing a C# POCO is to use a read-only field for the specific field that is causing problems, and apply the formatting and string casting through that.

using CsvHelper.Configuration.Attributes;

public class MyRecord
{
    [Ignore]
    public long Long => 0000012345;
    
    [Name("Long")]
    public string LongExcel => @$"=""{Long}""";
}

There are likely better ways to do this, including using the Excel extension library - but for anyone looking for a quick and dirty approach, this is one option.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top