开发者

Create CSV file from c#: extra character in excel

I create a CSV file from a C# application but the characters  are displayed in Excel and OpenOfficeCalc in the first cell but not in Notepad and Notepad++.

Here is my code:

StreamWriter streamWriter = new StreamWriter(new FileStream(filePath, FileMode.Create), Encoding.UTF8);
List<MyData> myData = GetMyData;

foreach(MyData md in myData)
{
    streamWriter.WriteLine(md.Date + "," + md.Data1 + "," + md.Data2 + "," + md.Data3 + "," + md.Data4);
}
streamWriter.Flush();
streamWriter.Close();

MyData is

public struct MyData
{
    public float Data1;
    public float Data2;
    public float Data3;
    public float Data4;
    public DateTime Date;
}

Here is the result in Notepad and Notepad++:

01/12/2010 00:04:00,0.08,78787.4,9.1,5
01/12/2010 00:09:00,0.07,78787.42,9.1,5
01/12/2010 00:14:00,0.06,78787.44,9.1,5
01/12/2010 00:19:00,1.45,78787.58,9.1,5
01/12/2010 00:24:00,2.13,78788.15,9.1,5
01/12/2010 00:29:00,1.72,78788.53,9,5
01/12/2010 00:34:00,0.89,78788.73,9,5

And in Excel and Calc:

01/12/2010 00:04:00   0.08    78787.4     9.1    5
01/12/10 00:09           0.07    78787.42    9.1    5
01/12/10 00:14           0.06    78787.44    9.1    5
01/12/10 00:19           开发者_运维问答1.45    78787.58    9.1    5
01/12/10 00:24           2.13    78788.15    9.1    5
01/12/10 00:29           1.72    78788.53    9      5
01/12/10 00:34           0.89    78788.73    9      5

Those 3 characters appears only once at the start of the file and then everything is as it should be.

My question is:

Where does  come from and how to remove it?

I have tried to write my output in a StringBuilder and to debug to see its content and it does not have those character.


This is the BOM for UTF8 encoding

Look at this question: Write text files without Byte Order Mark (BOM)?


You may want to specify the encoding type based on your input. StreamWriter.Encoding Property

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.encoding.aspx


I think that is BOM (unicode header). Specify ANSI encoding in constructor of StreamWriter. It is simple: Just set it to Encoding.Default.

update: If you must use UTF-8 and need to get rid of those 3 bytes at the beginning, use this: new UTF8Encoding(false). This way the writer will stay in UTF8, but won't write BOM.


Try to specify Encoding.ASCII instead of using Encoding.UTF8 when you create the StreamWriter

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜