0

I am exporting some generated Serial Code in 3 formats (with C# Asp.Net MVC): .txt, .csv and .xls. The thing is in .txt and .xls the Code is in the right format. But in .csv it loses its leading 0 if it starts with 0 and example:

183531982165

is shown like

1,83532E+11

This is the code snipped I use to fill the file:

public static byte[] CreateFile(SericalCodeModel scObj, myDB db)
    {
        using (System.IO.FileStream fs = new System.IO.File.Create(filePath))
        {
            using (System.IO.TextWriter wr = new System.IO.StreamWriter(fs))
            {
                List<List<string>> fileLines = db.Get<SerialCode>().GetSerialcodeOutDataToFile(scObj); // the db records
                foreach (List<string> fileLine in fileLines)
                {
                    wr.WriteLine(string.Join(";", fileLine));
                }
            }
        }
    }

This error occurs only when I open the file with Excel, otherwise, with any other editor like notepad it is shown how it is!

Why is that and how can I fix that error?

Cœur
  • 37,241
  • 25
  • 195
  • 267
arianit ax
  • 187
  • 1
  • 3
  • 13
  • 1
    csv files lack the formatting you are used to, so you have to give Excel instructions on how to interpret their content (text, numbers, etc..). For details, see https://stackoverflow.com/questions/137359/excel-csv-number-cell-format – Tony M Jul 25 '17 at 15:39
  • I tried to do something like they did in that thread with this "=" thing but didn't work. The thing is that only one column, that one with that Numeric code (serial code) has that formatting problem, the other columns are ok. Also when I change the formatting when the csv file is opened with Excel, the leading 0 are still missing. I edited the question with the code I use for getting the file filed with records. – arianit ax Jul 26 '17 at 12:49
  • What are you opening the CSV in? Open it in notepad - do you see the correct format? Excel is just messing you around. – Nick.Mc Jul 26 '17 at 13:31
  • @Nick.McDermaid yes, in every other tool like notepad, notepad++, the format is right, only in excel it is wrong. With cell formatting it can be fixed (even while the user should not bother to do so) but the leading 0 are missing! – arianit ax Jul 27 '17 at 06:53
  • 1
    So the question is: what is the actual purpose of the CSV file? You already have a.xls file for excel. This "issue" will occur with any CSV file. CSV is normally used for upload into other systems. It just coincidental that it opens in excel by default. To actually force formatting you could try surrounding it with quotes. But really the answer is: don't open this file in excel – Nick.Mc Jul 27 '17 at 06:56

0 Answers0