Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Export C# List to Csv file

I was trying to export my C# list to Csv file. All is set well. But the thing is field seperator is not working properly. its showing like, my string with " at the end (eg: 0000324df"). Here is my Controller code.

IEnumerable stockexpo = stockexp; // Assign value
        MemoryStream output = new MemoryStream();
        StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
        writer.Write("ItemNo,");
        writer.Write("Repeat Count");
        writer.WriteLine();
        foreach (StockResult order in stockexpo)
        {
            writer.Write(String.Format("{0:d}", order.ItemNumber));
            writer.Write(""");
            writer.Write(",");
            writer.Write(""");
            writer.Write(order.Count);
            writer.Write(""");
            writer.Write(",");
            writer.WriteLine();
        }
        writer.Flush();
        output.Position = 0;

        return File(output, "text/comma-separated-values", "stockexp.csv");

I need to know how i can seperate the field values appropriately. Anyone can help me for this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  writer.Write(""");

This line of code will be outputting a " every time. Why have it at all?

Also, I wouldn't have a comma before the WriteLine, since there is no need to delimit the end of the file.

IEnumerable stockexpo = stockexp; // Assign value
    MemoryStream output = new MemoryStream();
    StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
    writer.Write("ItemNo,");
    writer.Write("Repeat Count");
    writer.WriteLine();
    foreach (StockResult order in stockexpo)
    {
        writer.Write(order.ItemNumber);
        writer.Write(",");
        writer.Write(order.Count);
        writer.WriteLine();
    }
    writer.Flush();
    output.Position = 0;

    return File(output, "text/comma-separated-values", "stockexp.csv");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...