c# - 如何创建 CSV Excel 文件 C#?

标签 c# excel csv export

<分区>

我正在寻找用于创建 CSV Excel 文件的类。

预期功能:

  • 使用起来非常简单
  • 转义逗号和引号,以便 excel 能够很好地处理它们
  • 以时区格式导出日期和日期时间

你知道有什么类(class)能做到这一点吗?

最佳答案

我根据需要使用反射编写的略有不同的版本。我必须将对象列表导出到 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;

        }
    }

使用示例:(根据评论更新)

CsvExport<BusinessObject> csv= new CsvExport<BusinessObject>(GetBusinessObjectList());
Response.Write(csv.Export());

关于c# - 如何创建 CSV Excel 文件 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2422212/

相关文章:

python - Pandas :合并两个具有重复行的数据框

python - 关于 Python 上的 ETL 工作的问题/一般情况

java - 代码创建不同的不同结果读取csv文件和txt文件 - java

C# 泛型约束 : Is there a way to express is not a?

c# - RandomNumberGenerator 的正确使用

vba - VB 与 VBA 有什么区别?

VBA 声明日期/时间数据

c# - WebJob 使用多种方法抛出 FunctionIndexingException

javascript - 在 asp.net mvc 中使用 foreach 循环显示模态

excel - Excel 中的复杂查找