CSV Excel 파일을 만들기위한 클래스를 찾고 있습니다.
예상되는 기능 :
- 사용하기 매우 간단
- 쉼표와 따옴표를 이스케이프 처리하여 Excel에서 잘 처리합니다.
- 날짜 및 날짜 / 시간을 표준 시간대 형식으로 내 보냅니다.
이것을 할 수있는 수업이 있습니까?
답변
약간의 다른 버전으로 내 요구에 반영을 사용하여 썼습니다. 객체 목록을 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());
답변
용서 해주세요
그러나 공개 오픈 소스 저장소는 코드를 공유하고 공헌하고 수정하고 “이 문제를 해결했습니다.
그래서 주제 시작 코드와 모든 추가 사항으로 간단한 git-repository를 만들었습니다.
https://github.com/jitbit/CsvExport
또한 몇 가지 유용한 수정 사항을 직접 추가했습니다. 누구나 제안을 추가하고, 포크 등을 공헌 할 수 있습니다. 포크를 보내서 리포지토리에 다시 병합하십시오.
추신. Chris에 대한 모든 저작권 표시를 게시했습니다. @Chris이 아이디어에 반대하는 경우 알려주세요.
답변
CSV 파일을 읽고 쓰는 또 다른 좋은 솔루션은 파일 도우미 (오픈 소스)입니다.
답변
모든 foreach 루프 대신 string.Join을 사용하는 것은 어떻습니까?
답변
누구든지 IEnumerable의 확장 메소드로 변환하고 싶다면 :
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;
}
}
답변
이 수업에 큰 도움이됩니다. 간단하고 사용하기 쉽습니다. 내보내기의 첫 번째 행에 제목을 포함하도록 클래스를 수정했습니다. 내가 공유 할 것이라고 생각했다.
사용하다:
CsvExport myExport = new CsvExport();
myExport.addTitle = String.Format("Name: {0},{1}", lastName, firstName));
수업:
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());
}
}
