Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write tab separated csv file in c#

Tags:

c#

I am currently developing an application in C# where I need to write a tab separated CSV file from the data that it retrieves from a MySQL Database. The database retrieval works fine.

The problem that I am having is writing the file. Between each variable that I am writing I am using the \t which I thought put a tab into the csv, therefore when opening in excel each variable will be in its own cell.

However for some reason it is not doing this it just writes the whole line as one long string. Below is an example of the code that I am code that I have written:

while (reader.Read())
{
    int bankID = reader.GetInt16("ban_bankID");
    int userID = reader.GetInt16("ban_userID");
    string bankUsername = reader.GetString("ban_username");
    string accountName = reader.GetString("ban_accountName");
    string accountType = reader.GetString("ban_accountType");
    decimal overdraft = reader.GetDecimal("ban_overdraft");
    char defaultAccount = reader.GetChar("ban_defaultAccount");

    string line = bankID + "\t" + userID + "\t" + bankUsername + "\t" + accountName + "\t"
              + accountType + "\t" + overdraft + "\t" + defaultAccount + "\n";

    tw.WriteLine(line);

Thanks for your help with this problem.

like image 492
Boardy Avatar asked Nov 13 '10 01:11

Boardy


People also ask

How do I tab in a csv file?

You are able to import CSV or Tab-delimited Text files in ELAN: File > Import > CSV / Tab-delimited Text File.... In the dialog window browse to and select a file that contains CSV or Tab-delimited data and click Open. The second dialog window contains two sections (see Figure 69, “Import CSV / Tab-delimited Text”).


1 Answers

The format is correct, a CSV expects the file to be COMMA Separated. When saving a Tab delimited file, typically just a txt extension is used (or some people save as .tsv) etc.

If you look at the Save As options in excel the option is Text (Tab Delimited) .txt

If I open the output generated by your sample code (stubbing in the data) everything loads in to Excel 2007 as you would expect.

like image 78
Chris Baxter Avatar answered Sep 29 '22 08:09

Chris Baxter