Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建CSV Excel文件C#?_C#_Excel_Csv_Export - Fatal编程技术网

如何创建CSV Excel文件C#?

如何创建CSV Excel文件C#?,c#,excel,csv,export,C#,Excel,Csv,Export,我正在寻找一个创建CSV Excel文件的类 预期功能: 非常简单易用 转义逗号和引号,以便excel可以很好地处理它们 以时区验证格式导出日期和日期时间 你知道有哪个类能够做到这一点吗?另一个读写CSV文件的好方法是(开源)。使用string.Join而不是所有的foreach循环怎么样?你也可以使用ADO来实现这一点:这个类做得很好。简单易用。我修改了类以在导出的第一行中包含标题;我想我会分享: 使用: 类别: public class CsvExport { List<s

我正在寻找一个创建CSV Excel文件的类

预期功能:

  • 非常简单易用
  • 转义逗号和引号,以便excel可以很好地处理它们
  • 以时区验证格式导出日期和日期时间

你知道有哪个类能够做到这一点吗?

另一个读写CSV文件的好方法是(开源)。

使用string.Join而不是所有的foreach循环怎么样?

你也可以使用ADO来实现这一点:

这个类做得很好。简单易用。我修改了类以在导出的第一行中包含标题;我想我会分享:

使用:

类别:

public class CsvExport
{
    List<string> fields = new List<string>();

    public string addTitle { get; set; } // string for the first row of the export

    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> currentRow
    {
        get
        {
            return rows[rows.Count - 1];
        }
    }

    public object this[string field]
    {
        set
        {
            if (!fields.Contains(field)) fields.Add(field);
            currentRow[field] = value;
        }
    }

    public void AddRow()
    {
        rows.Add(new Dictionary<string, object>());
    }

    string MakeValueCsvFriendly(object value)
    {
        if (value == null) return "";
        if (value is Nullable && ((INullable)value).IsNull) return "";
        if (value is DateTime)
        {
            if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                return ((DateTime)value).ToString("yyyy-MM-dd");
            return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
        }
        string output = value.ToString();
        if (output.Contains(",") || output.Contains("\""))
            output = '"' + output.Replace("\"", "\"\"") + '"';
        return output;

    }

    public string Export()
    {
        StringBuilder sb = new StringBuilder();

        // if there is a title
        if (!string.IsNullOrEmpty(addTitle))
        {
            // escape chars that would otherwise break the row / export
            char[] csvTokens = new[] { '\"', ',', '\n', '\r' };

            if (addTitle.IndexOfAny(csvTokens) >= 0)
            {
                addTitle = "\"" + addTitle.Replace("\"", "\"\"") + "\"";
            }
            sb.Append(addTitle).Append(",");
            sb.AppendLine();
        }


        // The header
        foreach (string field in fields)
        sb.Append(field).Append(",");
        sb.AppendLine();

        // The rows
        foreach (Dictionary<string, object> row in rows)
        {
            foreach (string field in fields)
                sb.Append(MakeValueCsvFriendly(row[field])).Append(",");
            sb.AppendLine();
        }

        return sb.ToString();
    }

    public void ExportToFile(string path)
    {
        File.WriteAllText(path, Export());
    }

    public byte[] ExportToBytes()
    {
        return Encoding.UTF8.GetBytes(Export());
    }
}
公共类CsvExport
{
列表字段=新列表();
导出第一行的公共字符串addTitle{get;set;}//string
列表行=新列表();
字典当前行
{
得到
{
返回行[rows.Count-1];
}
}
公共对象[字符串字段]
{
设置
{
如果(!fields.Contains(field))fields.Add(field);
currentRow[字段]=值;
}
}
public void AddRow()
{
添加(新字典());
}
字符串MakeValueCsvFriendly(对象值)
{
如果(value==null)返回“”;
if(value可为null&((INullable)value).IsNull)返回“”;
if(值为DateTime)
{
如果(((DateTime)值).TimeOfDay.TotalSeconds==0)
返回((日期时间)值).ToString(“yyyy-MM-dd”);
返回((日期时间)值).ToString(“yyyy-MM-dd-HH:MM:ss”);
}
字符串输出=value.ToString();
if(output.Contains(“,”)| output.Contains(“\”)
输出='“'+输出。替换(“\”,“\”)+';
返回输出;
}
公共字符串导出()
{
StringBuilder sb=新的StringBuilder();
//如果有标题
如果(!string.IsNullOrEmpty(addTitle))
{
//转义字符,否则会破坏行/导出
char[]csvTokens=new[]{'\',',','\n','\r'};
if(addTitle.IndexOfAny(csvTokens)>=0)
{
addTitle=“\”+addTitle.Replace(“\”,“\”)+“\”;
}
sb.Append(addTitle)。Append(“,”);
(某人);
}
//标题
foreach(字段中的字符串字段)
sb.Append(字段)。Append(“,”);
(某人);
//争吵
foreach(字典行中的行)
{
foreach(字段中的字符串字段)
sb.Append(MakeValueCsvFriendly(行[字段])。Append(“,”);
(某人);
}
使某人返回字符串();
}
公共void导出文件(字符串路径)
{
writealText(路径,Export());
}
公共字节[]导出字节()
{
返回Encoding.UTF8.GetBytes(Export());
}
}

根据我的需要使用反射编写的版本略有不同。我必须将对象列表导出到csv。以防将来有人想用它

public class CsvExport<T> where T: class
    {
        public List<T> Objects;

        public CsvExport(List<T> objects)
        {
            Objects = objects;
        }

        public string Export()
        {
            return Export(true);
        }

        public string Export(bool includeHeaderLine)
        {

            StringBuilder sb = new StringBuilder();
            //Get properties using reflection.
            IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();

            if (includeHeaderLine)
            {
                //add header line.
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    sb.Append(propertyInfo.Name).Append(",");
                }
                sb.Remove(sb.Length - 1, 1).AppendLine();
            }

            //add value for each property.
            foreach (T obj in Objects)
            {               
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj, null))).Append(",");
                }
                sb.Remove(sb.Length - 1, 1).AppendLine();
            }

            return sb.ToString();
        }

        //export to a file.
        public void ExportToFile(string path)
        {
            File.WriteAllText(path, Export());
        }

        //export as binary data.
        public byte[] ExportToBytes()
        {
            return Encoding.UTF8.GetBytes(Export());
        }

        //get the csv value for field.
        private string MakeValueCsvFriendly(object value)
        {
            if (value == null) return "";
            if (value is Nullable && ((INullable)value).IsNull) return "";

            if (value is DateTime)
            {
                if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                    return ((DateTime)value).ToString("yyyy-MM-dd");
                return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
            }
            string output = value.ToString();

            if (output.Contains(",") || output.Contains("\""))
                output = '"' + output.Replace("\"", "\"\"") + '"';

            return output;

        }
    }
公共类csveexport,其中T:class
{
公开列出对象;
公共CsvExport(列出对象)
{
对象=对象;
}
公共字符串导出()
{
退货出口(真实);
}
公共字符串导出(bool includeHeaderLine)
{
StringBuilder sb=新的StringBuilder();
//使用反射获取属性。
IList propertyInfos=typeof(T).GetProperties();
如果(包括领头线)
{
//添加标题行。
foreach(PropertyInfo PropertyInfo in propertyInfos中的PropertyInfo)
{
sb.Append(propertyInfo.Name);
}
删除(sb.Length-1,1.AppendLine();
}
//为每个属性添加值。
foreach(对象中的对象)
{               
foreach(PropertyInfo PropertyInfo in propertyInfos中的PropertyInfo)
{
sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj,null)).Append(“,”);
}
删除(sb.Length-1,1.AppendLine();
}
使某人返回字符串();
}
//导出到文件。
公共void导出文件(字符串路径)
{
writealText(路径,Export());
}
//导出为二进制数据。
公共字节[]导出字节()
{
返回Encoding.UTF8.GetBytes(Export());
}
//获取字段的csv值。
私有字符串MakeValueCsvFriendly(对象值)
{
如果(value==null)返回“”;
if(value可为null&((INullable)value).IsNull)返回“”;
if(值为DateTime)
{
如果(((DateTime)值).TimeOfDay.TotalSeconds==0)
返回((日期时间)值).ToString(“yyyy-MM-dd”);
返回((日期时间)值).ToString(“yyyy-MM-dd-HH:MM:ss”);
}
字符串输出=value.ToString();
if(output.Contains(“,”)| output.Contains(“\”)
输出='“'+输出。替换(“\”,“\”)+';
返回输出;
}
}
用法示例:(根据注释更新)

CsvExport csv=新的CsvExport(GetBusinessObjectList());
Response.Write(csv.Export());

我添加了ExportToStream,这样csv就不必先保存到硬盘上

public Stream ExportToStream()
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(Export(true));
    writer.Flush();
    stream.Position = 0;
    return stream;
}
我补充说

public void ExportToFile(string path, DataTable tabela)
{

     DataColumnCollection colunas = tabela.Columns;

     foreach (DataRow linha in tabela.Rows)
     {

           this.AddRow();

           foreach (DataColumn coluna in colunas)

           {

               this[coluna.ColumnName] = linha[coluna];

           }

      }
      this.ExportToFile(path);

}
以前的代码不适用于旧的.NET版本。对于框架的3.5版本,请使用此其他版本:

        public void ExportToFile(string path)
    {
        bool abort = false;
        bool exists = false;
        do
        {
            exists = File.Exists(path);
            if (!exists)
            {
                if( !Convert.ToBoolean( File.CreateText(path) ) )
                        abort = true;
            }
        } while (!exists || abort);

        if (!abort)
        {
            //File.OpenWrite(path);
            using (StreamWriter w = File.AppendText(path))
            {
                w.WriteLine("hello");
            }

        }

        //File.WriteAllText(path, Export());
    }

有一个用于CSV的开源库,您可以使用nuget获得它:

非常感谢! 我将该类修改为:

  • 使用变量分隔符,而不是在代码中硬编码
  • 全部替换
    MakeValueCsvFriendly中的换行符(\n\r\n\r)public void ExportToFile(string path, DataTable tabela)
    {
    
         DataColumnCollection colunas = tabela.Columns;
    
         foreach (DataRow linha in tabela.Rows)
         {
    
               this.AddRow();
    
               foreach (DataColumn coluna in colunas)
    
               {
    
                   this[coluna.ColumnName] = linha[coluna];
    
               }
    
          }
          this.ExportToFile(path);
    
    }
    
            public void ExportToFile(string path)
        {
            bool abort = false;
            bool exists = false;
            do
            {
                exists = File.Exists(path);
                if (!exists)
                {
                    if( !Convert.ToBoolean( File.CreateText(path) ) )
                            abort = true;
                }
            } while (!exists || abort);
    
            if (!abort)
            {
                //File.OpenWrite(path);
                using (StreamWriter w = File.AppendText(path))
                {
                    w.WriteLine("hello");
                }
    
            }
    
            //File.WriteAllText(path, Export());
        }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Data.SqlTypes;
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;
    
        public class CsvExport
        {
    
            public char delim = ';';
            /// <summary>
            /// To keep the ordered list of column names
            /// </summary>
            List<string> fields = new List<string>();
    
            /// <summary>
            /// The list of rows
            /// </summary>
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    
            /// <summary>
            /// The current row
            /// </summary>
            Dictionary<string, object> currentRow { get { return rows[rows.Count - 1]; } }
    
            /// <summary>
            /// Set a value on this column
            /// </summary>
            public object this[string field]
            {
                set
                {
                    // Keep track of the field names, because the dictionary loses the ordering
                    if (!fields.Contains(field)) fields.Add(field);
                    currentRow[field] = value;
                }
            }
    
            /// <summary>
            /// Call this before setting any fields on a row
            /// </summary>
            public void AddRow()
            {
                rows.Add(new Dictionary<string, object>());
            }
    
            /// <summary>
            /// Converts a value to how it should output in a csv file
            /// If it has a comma, it needs surrounding with double quotes
            /// Eg Sydney, Australia -> "Sydney, Australia"
            /// Also if it contains any double quotes ("), then they need to be replaced with quad quotes[sic] ("")
            /// Eg "Dangerous Dan" McGrew -> """Dangerous Dan"" McGrew"
            /// </summary>
            string MakeValueCsvFriendly(object value)
            {
                if (value == null) return "";
                if (value is INullable && ((INullable)value).IsNull) return "";
                if (value is DateTime)
                {
                    if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                        return ((DateTime)value).ToString("yyyy-MM-dd");
                    return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
                }
                string output = value.ToString();
                if (output.Contains(delim) || output.Contains("\""))
                    output = '"' + output.Replace("\"", "\"\"") + '"';
                if (Regex.IsMatch(output,  @"(?:\r\n|\n|\r)"))
                    output = string.Join(" ", Regex.Split(output, @"(?:\r\n|\n|\r)"));
                return output;
            }
    
            /// <summary>
            /// Output all rows as a CSV returning a string
            /// </summary>
            public string Export()
            {
                StringBuilder sb = new StringBuilder();
    
                // The header
                foreach (string field in fields)
                    sb.Append(field).Append(delim);
                sb.AppendLine();
    
                // The rows
                foreach (Dictionary<string, object> row in rows)
                {
                    foreach (string field in fields)
                        sb.Append(MakeValueCsvFriendly(row[field])).Append(delim);
                    sb.AppendLine();
                }
    
                return sb.ToString();
            }
    
            /// <summary>
            /// Exports to a file
            /// </summary>
            public void ExportToFile(string path)
            {
                File.WriteAllText(path, Export());
            }
    
            /// <summary>
            /// Exports as raw UTF8 bytes
            /// </summary>
            public byte[] ExportToBytes()
            {
                return Encoding.UTF8.GetBytes(Export());
    
            }
    
        }
    
    protected void lnkExport_OnClick(object sender, EventArgs e)
    {
    
        string filename = strFileName = "Export.csv";
    
        DataTable dt = obj.GetData();  
    
    // call the content and load it into the datatable
    
        strFileName = Server.MapPath("Downloads") + "\\" + strFileName;
    
    // creating a file in the downloads folder in your solution explorer
    
        TextWriter tw = new StreamWriter(strFileName);
    
    // using the built in class textwriter for writing your content in the exporting file
    
        string strData = "Username,Password,City";
    
    // above line is the header for your exported file. So add headings for your coloumns in excel(.csv) file and seperate them with ","
    
        strData += Environment.NewLine;
    
    // setting the environment to the new line
    
        foreach (DataRow dr in dt.Rows)
        {
           strData += dr["Username"].ToString() + "," + dr["Password"].ToString() + "," +      dr["City"].ToString();
           strData += Environment.NewLine;
        }
    
    // everytime when loop execute, it adds a line into the file
        tw.Write(strData);
    
    // writing the contents in file
        tw.Close();
    
    // closing the file
        Response.Redirect("Downloads/" + filename);
    
    // exporting the file to the user as a popup to save as....
    }
    
    public static class ListExtensions
    {
        public static string ExportAsCSV<T>(this IEnumerable<T> listToExport, bool includeHeaderLine, string delimeter)
        {
            StringBuilder sb = new StringBuilder();
    
            IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();
    
            if (includeHeaderLine)
            {
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    sb.Append(propertyInfo.Name).Append(",");
                }
                sb.Remove(sb.Length - 1, 1).AppendLine();
            }
    
            foreach (T obj in listToExport)
            {
                T localObject = obj;
    
                var line = String.Join(delimeter, propertyInfos.Select(x => SanitizeValuesForCSV(x.GetValue(localObject, null), delimeter)));
    
                sb.AppendLine(line);
            }
    
            return sb.ToString();
        }
    
        private static string SanitizeValuesForCSV(object value, string delimeter)
        {
            string output;
    
            if (value == null) return "";
    
            if (value is DateTime)
            {
                output = ((DateTime)value).ToLongDateString();
            }
            else
            {
                output = value.ToString();                
            }
    
            if (output.Contains(delimeter) || output.Contains("\""))
                output = '"' + output.Replace("\"", "\"\"") + '"';
    
            output = output.Replace("\n", " ");
            output = output.Replace("\r", "");
    
            return output;
        }
    }
    
    static void Main(string[] args)
    {
        var export = new CsvExport();
    
        export.AddRow();
        export["Region"] = "New York, USA";
        export["Sales"] = 100000;
        export["Date Opened"] = new DateTime(2003, 12, 31);
    
        export.AddRow();
        export["Region"] = "Sydney \"in\" Australia";
        export["Sales"] = 50000;
        export["Date Opened"] = new DateTime(2005, 1, 1, 9, 30, 0);
        export["Balance"] = 3.45f;  //Exception is throwed for this new column
    
        export.ExportToFile("Somefile.csv");
    }
    
    static void Main(string[] args)
    {
        var export = new CsvExporter();
    
        export.AddRow(new {A = 12, B = "Empty"});
        export.AddRow(new {A = 34.5f, D = false});
    
        export.ExportToFile("File.csv");
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var writer = new CsvWriter<Person>("Persons.csv");
    
            writer.AddFormatter<DateTime>(d => d.ToString("MM/dd/yyyy"));
    
            writer.WriteHeaders();
            writer.WriteRows(GetPersons());
    
            writer.Flush();
            writer.Close();
        }
    
        private static IEnumerable<Person> GetPersons()
        {
            yield return new Person
                {
                    FirstName = "Jhon", 
                    LastName = "Doe", 
                    Sex = 'M'
                };
    
            yield return new Person
                {
                    FirstName = "Jhane", 
                    LastName = "Doe",
                    Sex = 'F',
                    BirthDate = DateTime.Now
                };
            }
        }
    
    
        class Person
        {
            public string FirstName { get; set; }
    
            public string LastName { get; set; }
    
            public char Sex  { get; set; }
    
            public DateTime BirthDate { get; set; }
        }