CSV帮助程序无法写入文件

时间:2015-06-29 16:42:21

标签: c# excel csv streamwriter csvhelper

我一直试图让CSV Helper写入文件。当我运行DownloadRegistrantsCsv时,它会使用正确的名称和其他所有内容下载文件,但它从不向它写入任何内容。

public async Task<Stream> GetDownloadStreamAsync(int id)
{

    var memoryStream = new MemoryStream();
    var streamWriter = new StreamWriter(memoryStream);
    var streamReader = new StreamReader(memoryStream);
    var csvHelper = new CsvHelper.CsvWriter(streamWriter);
    csvHelper.WriteRecord(new EventRegistrant { FirstName = "Max" });
    await memoryStream.FlushAsync();
    memoryStream.Position = 0;

    return memoryStream;
}

public async Task<ActionResult> DownloadRegistrantsCsv(int id)
{
    var @event = await _service.GetAsync(id, true);
    if (@event == null)
        return HttpNotFound();

    var stream = await _service.GetDownloadStreamAsync(id);
    return File(stream, "application/txt", "test" + ".csv");
}

我也尝试过使用CSV Helper的文档,我甚至无法编写。这就是我得到的......

// Copyright 2009-2015 Josh Close and Contributors
// This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0.
// See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0.
// http://csvhelper.com
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Web.Script.Serialization;
using CsvHelper.Configuration;
using CsvHelper.TypeConversion;

namespace CsvHelper.Example
{
    class Program
    {
        private const string columnSeparator = ":";

        static void Main(string[] args)
        {
            //ReadRawFieldsByIndex();
            //ReadRawFieldsByName();
            //ReadFieldsByIndex();
            //ReadRecordsNoAttributes();
            //ReadRecordsWithAttributes();
            //ReadAllRecords();

            //WriteRawFields();
            //WriteFields();
            WriteRecordsNoAttributes();
            //WriteRecordsWithAttributes();
            WriteAllRecords();

            Console.ReadKey();
        }

        public static void ReadRawFieldsByIndex()
        {
            Console.WriteLine("Raw fields by index:");

            using (var reader = new CsvReader(new StreamReader(GetDataStream(true, true))))
            {
                while (reader.Read())
                {
                    Console.Write(reader.GetField(0) + columnSeparator);
                    Console.Write(reader.GetField(1) + columnSeparator);
                    Console.Write(reader.GetField(2) + columnSeparator);
                    Console.WriteLine(reader.GetField(3));
                }
            }
            Console.WriteLine();
        }

        public static void ReadRawFieldsByName()
        {
            Console.WriteLine("Raw fields by name:");

            using (var reader = new CsvReader(new StreamReader(GetDataStream(true, true))))
            {
                while (reader.Read())
                {
                    Console.Write(reader.GetField("String Column") + columnSeparator);
                    Console.Write(reader.GetField("Int Column") + columnSeparator);
                    Console.Write(reader.GetField("Guid Column") + columnSeparator);
                    Console.Write(reader.GetField("Does Not Exist Column") + columnSeparator);
                    Console.WriteLine(reader.GetField("Custom Type Column"));
                }
            }
            Console.WriteLine();
        }

        public static void ReadFieldsByIndex()
        {
            Console.WriteLine("Fields by index:");

            var customTypeTypeConverter = new CustomTypeTypeConverter();

            using (var reader = new CsvReader(new StreamReader(GetDataStream(true, true))))
            {
                while (reader.Read())
                {
                    Console.Write(reader.GetField<string>(0) + columnSeparator);
                    Console.Write(reader.GetField<int>("Int Column") + columnSeparator);
                    Console.Write(reader.GetField<Guid>(2) + columnSeparator);
                    Console.WriteLine(reader.GetField<CustomType>(3, customTypeTypeConverter));
                }
            }
            Console.WriteLine();
        }

        public static void ReadRecordsNoAttributes()
        {
            Console.WriteLine("Records no attributes:");

            using (var reader = new CsvReader(new StreamReader(GetDataStream(true, false))))
            {
                while (reader.Read())
                {
                    Console.WriteLine(reader.GetRecord<CustomObject>());
                }
            }
            Console.WriteLine();
        }

        public static void ReadRecordsWithAttributes()
        {
            Console.WriteLine("Records with attributes:");

            using (var reader = new CsvReader(new StreamReader(GetDataStream(true, true))))
            {
                reader.Configuration.RegisterClassMap<CustomObjectWithMappingMap>();

                while (reader.Read())
                {
                    Console.WriteLine(reader.GetRecord<CustomObjectWithMapping>());
                }
            }
            Console.WriteLine();
        }

        public static void ReadAllRecords()
        {
            Console.WriteLine("All records:");

            using (var reader = new CsvReader(new StreamReader(GetDataStream(true, false))))
            {
                var records = reader.GetRecords<CustomObject>();
                foreach (var record in records)
                {
                    Console.WriteLine(record);
                }
            }
            Console.WriteLine();
        }

        public static void WriteRawFields()
        {
            Console.WriteLine("Write raw fields");

            using (var memoryStream = new MemoryStream())
            using (var streamWriter = new StreamWriter(memoryStream))
            using (var streamReader = new StreamReader(memoryStream))
            using (var writer = new CsvWriter(streamWriter))
            {
                writer.WriteField("String Column");
                writer.WriteField("Int Column");
                writer.WriteField("Guid Column");
                writer.WriteField("Custom Type Column");
                writer.NextRecord();

                writer.WriteField("one");
                writer.WriteField((1).ToString());
                writer.WriteField(Guid.NewGuid().ToString());
                writer.WriteField((new CustomType { First = 1, Second = 2, Third = 3 }).ToString());
                writer.NextRecord();

                memoryStream.Position = 0;

                Console.WriteLine(streamReader.ReadToEnd());
            }
            Console.WriteLine();
        }

        public static void WriteFields()
        {
            Console.WriteLine("Write fields");

            using (var memoryStream = new MemoryStream())
            using (var streamWriter = new StreamWriter(memoryStream))
            using (var streamReader = new StreamReader(memoryStream))
            using (var writer = new CsvWriter(streamWriter))
            {
                writer.WriteField("String Column");
                writer.WriteField("Int Column");
                writer.WriteField("Guid Column");
                writer.WriteField("Custom Type Column");
                writer.NextRecord();

                writer.WriteField("one");
                writer.WriteField(1);
                writer.WriteField(Guid.NewGuid());
                writer.WriteField(new CustomType { First = 1, Second = 2, Third = 3 });
                writer.NextRecord();

                memoryStream.Position = 0;

                Console.WriteLine(streamReader.ReadToEnd());
            }
            Console.WriteLine();
        }

        public static void WriteRecordsNoAttributes()
        {
            Console.WriteLine("Write records no attributes:");

            var records = new List<CustomObject>
            {
                new CustomObject
                {
                    CustomTypeColumn = new CustomType
                    {
                        First = 1,
                        Second = 2,
                        Third = 3,
                    },
                    GuidColumn = Guid.NewGuid(),
                    IntColumn = 1,
                    StringColumn = "one",
                },
                new CustomObject
                {
                    CustomTypeColumn = new CustomType
                    {
                        First = 4,
                        Second = 5,
                        Third = 6,
                    },
                    GuidColumn = Guid.NewGuid(),
                    IntColumn = 2,
                    StringColumn = "two",
                },
            };

            using (var memoryStream = new MemoryStream())
            using (var streamWriter = new StreamWriter(memoryStream))
            using (var streamReader = new StreamReader(memoryStream))
            using (var writer = new CsvWriter(streamWriter))
            {
                foreach (var record in records)
                {
                    writer.WriteRecord(record);
                }

                memoryStream.Position = 0;

                Console.WriteLine(streamReader.ReadToEnd());
            }
            Console.WriteLine();
        }

        public static void WriteRecordsWithAttributes()
        {
            Console.WriteLine("Write records with attributes:");

            var records = new List<CustomObjectWithMapping>
            {
                new CustomObjectWithMapping
                {
                    CustomTypeColumn = new CustomType
                    {
                        First = 1,
                        Second = 2,
                        Third = 3,
                    },
                    GuidColumn = Guid.NewGuid(),
                    IntColumn = 1,
                    StringColumn = "one",
                },
                new CustomObjectWithMapping
                {
                    CustomTypeColumn = new CustomType
                    {
                        First = 4,
                        Second = 5,
                        Third = 6,
                    },
                    GuidColumn = Guid.NewGuid(),
                    IntColumn = 2,
                    StringColumn = "two",
                },
            };

            using (var memoryStream = new MemoryStream())
            using (var streamWriter = new StreamWriter(memoryStream))
            using (var streamReader = new StreamReader(memoryStream))
            using (var writer = new CsvWriter(streamWriter))
            {
                foreach (var record in records)
                {
                    writer.WriteRecord(record);
                }

                memoryStream.Position = 0;

                Console.WriteLine(streamReader.ReadToEnd());
            }
            Console.WriteLine();
        }

        public static void WriteAllRecords()
        {
            Console.WriteLine("Write all records with attributes:");

            var records = new List<CustomObjectWithMapping>
            {
                new CustomObjectWithMapping
                {
                    CustomTypeColumn = new CustomType
                    {
                        First = 1,
                        Second = 2,
                        Third = 3,
                    },
                    GuidColumn = Guid.NewGuid(),
                    IntColumn = 1,
                    StringColumn = "one",
                },
                new CustomObjectWithMapping
                {
                    CustomTypeColumn = new CustomType
                    {
                        First = 4,
                        Second = 5,
                        Third = 6,
                    },
                    GuidColumn = Guid.NewGuid(),
                    IntColumn = 2,
                    StringColumn = "two",
                },
            };

            using (var memoryStream = new MemoryStream())
            using (var streamWriter = new StreamWriter(memoryStream))
            using (var streamReader = new StreamReader(memoryStream))
            using (var writer = new CsvWriter(streamWriter))
            {
                writer.Configuration.RegisterClassMap<CustomObjectWithMappingMap>();
                writer.WriteRecords(records as IEnumerable);

                memoryStream.Position = 0;

                Console.WriteLine(streamReader.ReadToEnd());
            }
            Console.WriteLine();
        }

        public static MemoryStream GetDataStream(bool hasHeader, bool hasSpacesInHeaderNames)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            if (hasHeader)
            {
                var header = hasSpacesInHeaderNames
                                ? "String Column,Int Column,Guid Column,Custom Type Column"
                                : "StringColumn,IntColumn,GuidColumn,CustomTypeColumn";
                writer.WriteLine(header);
            }
            writer.WriteLine("one,1,{0},1|2|3", Guid.NewGuid());
            writer.WriteLine("two,2,{0},4|5|6", Guid.NewGuid());
            writer.WriteLine("\"this, has a comma\",2,{0},7|8|9", Guid.NewGuid());
            writer.WriteLine("\"this has \"\"'s\",4,{0},10|11|12", Guid.NewGuid());
            writer.Flush();
            stream.Position = 0;

            return stream;
        }

        public class CustomType
        {
            public int First { get; set; }
            public int Second { get; set; }
            public int Third { get; set; }

            public override string ToString()
            {
                var serializer = new JavaScriptSerializer();
                return serializer.Serialize(this);
            }
        }

        public class CustomTypeTypeConverter : ITypeConverter
        {
            public string ConvertToString(TypeConverterOptions options, object value)
            {
                var obj = (CustomType)value;
                return string.Format("{0}|{1}|{2}", obj.First, obj.Second, obj.Third);
            }

            public object ConvertFromString(TypeConverterOptions options, string text)
            {
                var values = ((string)text).Split('|');

                var obj = new CustomType
                {
                    First = int.Parse(values[0]),
                    Second = int.Parse(values[1]),
                    Third = int.Parse(values[2]),
                };
                return obj;
            }

            public bool CanConvertFrom(Type type)
            {
                throw new NotImplementedException();
            }

            public bool CanConvertTo(Type type)
            {
                throw new NotImplementedException();
            }
        }

        public class CustomObject
        {
            public CustomType CustomTypeColumn { get; set; }
            public Guid GuidColumn { get; set; }
            public int IntColumn { get; set; }
            public string StringColumn { get; set; }

            public override string ToString()
            {
                var serializer = new JavaScriptSerializer();
                return serializer.Serialize(this);
            }
        }

        public class CustomObjectWithMapping
        {
            public CustomType CustomTypeColumn { get; set; }

            public Guid GuidColumn { get; set; }

            public int IntColumn { get; set; }

            public string StringColumn { get; set; }

            public string IgnoredColumn { get; set; }

            //public override string ToString()
            //{
            //    var serializer = new JavaScriptSerializer();
            //    return serializer.Serialize(this);
            //}
        }

        public sealed class CustomObjectWithMappingMap : CsvClassMap<CustomObjectWithMapping>
        {
            public CustomObjectWithMappingMap()
            {
                Map(m => m.CustomTypeColumn).Name("Custom Type Column").Index(3).TypeConverter<CustomTypeTypeConverter>();
                Map(m => m.GuidColumn).Name("Guid Column").Index(2);
                Map(m => m.IntColumn).Name("Int Column").Index(1);
                Map(m => m.StringColumn).Name("String Column").Index(0);
            }
        }
    }
}

有人能指出我可能遗失或做错的事吗?

2 个答案:

答案 0 :(得分:1)

如果你有一个DataTable,你可以将它转换为逗号分隔值这样的字符串列表......

/// <summary>
/// Creates a comma separated value string from a datatable.
/// </summary>
public static string ToCSV(DataTable table) 
{
    StringBuilder csv = new StringBuilder();
    for(int i = 0; i < table.Columns.Count ;i++) // process the column headers
    {
        if (i > 0)
            csv.Append(",");
        csv.Append(_FormatToCSVField(table.Columns[i].ColumnName));
    }
    if (table.Columns.Count > 0)
        csv.Append("\r\n");
    for (int i = 0; i < table.Rows.Count; i++) // process the row data
    {
        for (int j = 0; j < table.Columns.Count; j++) // process each field in the data row.
        {
            if (j > 0) 
                csv.Append(",");
            csv.Append(_FormatToCSVField(table.Rows[i][j].ToString()));
        }
        csv.Append("\r\n");
    }
    return csv.ToString();
}
private static string _FormatToCSVField(string unformattedField)
{
    return "\"" + unformattedField.Replace("\"", "\"\"") + "\"";
}

或者如果你没有DataTable;取你创建的逗号分隔值(CSV)字符串列表&#34; row1列1,row1 column2,row1 column3,\ r \ n,row2,colum1 ......等...&#34;

并将其保存为CSV文件,如下所示......

            //Your CSV String
        string WhatToWrite =  "row1 column 1, row1 column2, row1 column3, \r\n";

        //Convert your CSV String to byte[]
        byte[] PutWhatToWriteIntoBytes = Encoding.GetEncoding("iso-8859-1").GetBytes(WhatToWrite);

        //Write the byte[] to CSV readable by excel
        string filename = "WhatYouWantToCallYourFile" + ".csv";
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", filename.ToString());
        Response.Clear();
        Response.BinaryWrite(PutWhatToWriteIntoBytes);
        Response.End();

很难遵循所有代码。你究竟想要写一个CSV到底是什么...得到那个;检查它是否好。然后写入文件。确定你是在写一个空字符串,还是写作正在丢失字符串

答案 1 :(得分:0)

如果您仍想使用CSV Helper

,则刷新流编写器对我有用