在c#中写入制表符分隔的csv文件

时间:2010-11-13 01:48:16

标签: c#

我目前正在使用C#开发一个应用程序,我需要从它从MySQL数据库中检索的数据中编写一个制表符分隔的CSV文件。数据库检索工作正常。

我遇到的问题是写文件。在我写的每个变量之间,我正在使用\ t,我认为将标签放入csv中,因此当在excel中打开时,每个变量都将在其自己的单元格中。

然而由于某种原因,它没有这样做,它只是将整行写为一个长字符串。下面是我编写的代码示例:

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);

感谢您对此问题的帮助。

3 个答案:

答案 0 :(得分:6)

格式正确,CSV要求文件为COMMA分隔。保存制表符分隔文件时,通常只使用txt扩展名(或者某些人保存为.tsv)等。

如果查看excel中的“另存为”选项,则选项为“文本(制表符分隔)”.txt

如果我打开示例代码生成的输出(在数据中存根),所有内容都会按预期加载到Excel 2007中。

答案 1 :(得分:1)

您应该使用文本导入向导:数据/文本。从那里,您可以将分隔符指定为选项卡。

答案 2 :(得分:1)

问题在于您的编码 您没有显示TextWriter实例,但它应该如下所示:

TextWriter tw = new Stream(filename, false, Encoding.ASCII);  
相关问题