<分区>
我正在寻找用于创建 CSV Excel 文件的类。
预期功能:
- 使用起来非常简单
- 转义逗号和引号,以便 excel 能够很好地处理它们
- 以时区格式导出日期和日期时间
你知道有什么类(class)能做到这一点吗?
<分区>
我正在寻找用于创建 CSV 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/