Search code examples
c#excelexport-to-excelcsv

exporting a comma separated values text file to use in excel


In my C# winforms program I want to make an export function that will create a comma separated text file or csv. I am not sure about the logic of how to do this the best way. My exported file will be like this :

Family Name, First Name, Sex, Age
Dekker, Sean, Male, 23
Doe, John, Male, 40

So the first line I want to be the name of the columns, and the rest should be treated as values. Is it ok in this way for later usage? Or I should not include column names?

Would be nice to hear your experiences about this!


Solution

  • Sean,

    sorry don't have enough privilege points to comment directly on your post. I think you may be confusing CSV and Excel files here. A CSV is simply a text file where each value is separated by a comma, there is no special formating etc. Excel will display CSV files since it knows how to open them but you can just as easily open them in notepad.

    Excel .xslx files are different and can contain all sorts of different formats, charts etc. To format these files its important to understand that .xslx files are essentially zips. So the first place to start is to create an excel file with some data, save it and then rename the extension to .zip

    Open the zip file created now and you will see a number of different folders and files, of these the most important for your purposes is the XL directory. In this folder you will see a shared strings xml file and a worksheets folder.

    Lets start by going into the worksheet folder and opening sheet1.xml. Look for the line that says "

    If there is text in this column, i.e. data that excel should read as text then you will have something like 0. This indicates that cell A1 is of type string t="s" and that the value is to be found as the first value in the SharedStrings.xml file 0

    If there is a number in the cell then you may have something like 234. In this case Excel knows to use the value 234 in this cell.

    So in your case you will need to do the following:

    1: create the excel document in C# - there are a number of libraries available for this

    2: Open the excel file as a zip

    3: Modify in your case the styles and worksheets xml files

    4: Save the document