我正在尝试将数据从对象列表导出到csv文件。我设法创建了文件并创建了第一行,但是我需要为每个循环创建一些循环来遍历每个对象。
这是我的代码:
string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
string delimter = ",";
string[][] output = new string[][] {
new string[] {"TEST1","TEST2"}
};
int length = output.GetLength(0);
StringBuilder sb = new StringBuilder();
for (int index = 0; index < length; index++)
{
sb.AppendLine(string.Join(delimter, output[index]));
File.AppendAllText(filePath, sb.ToString());
}
有没有办法创建这个文件并使用循环遍历所有对象并将它们显示在文件中。
答案 0 :(得分:17)
以下是解决方案:
string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
string delimter = ",";
List<string[]> output = new List<string[]>();
//flexible part ... add as many object as you want based on your app logic
output.Add(new string[] {"TEST1","TEST2"});
output.Add(new string[] {"TEST3","TEST4"});
int length = output.Count;
using (System.IO.TextWriter writer = File.CreateText(filePath))
{
for (int index = 0; index < length; index++)
{
writer.WriteLine(string.Join(delimter, output[index]));
}
}
答案 1 :(得分:5)
假设obj是String的List我通常使用这个
System.IO.File.WriteAllLines(stringFilePath, obj.ToArray());
答案 2 :(得分:2)
如果你想要一个遍历列表中每个项目的通用扩展,将它添加到一个新行并使用getter遍历每个公共属性,并在该行的每个属性上创建一个逗号分隔的字段列表,你可以使用我的根据{{3}}或my tip, here进行扩展,在列表中调用扩展名,如下所示:
function CreatePizzaDropdownList()
{
$pizzaModel = new PizzaModel();
$result = "<form action = '' method = 'post' width = '200px'>
please select a type:
<select name = 'types'>
<option value = '%'>All</option>
" . $this->CreateOptionValues($pizzaModel->GetPizzaByTypes()).
"</select>
<input type = 'submit' value = 'Search'/>
</form>";
return $result;
}
以下完整代码
MyList.ToDelimitedText(",", true);
在这些测试中可以找到调用代码的示例:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Gists.Extensions.ListOfTExtentions
{
public static class ListOfTExtentions
{
/// <summary>
/// Converst this instance to delimited text.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance">The instance.</param>
/// <param name="delimiter">The delimiter.</param>
/// <param name="trimTrailingNewLineIfExists">
/// If set to <c>true</c> then trim trailing new line if it exists.
/// </param>
/// <returns></returns>
public static string ToDelimitedText<T>(this List<T> instance,
string delimiter,
bool trimTrailingNewLineIfExists = false)
where T : class, new()
{
int itemCount = instance.Count;
if (itemCount == 0) return string.Empty;
var properties = GetPropertiesOfType<T>();
int propertyCount = properties.Length;
var outputBuilder = new StringBuilder();
for (int itemIndex = 0; itemIndex < itemCount; itemIndex++)
{
T listItem = instance[itemIndex];
AppendListItemToOutputBuilder(outputBuilder, listItem, properties, propertyCount, delimiter);
AddNewLineIfRequired(trimTrailingNewLineIfExists, itemIndex, itemCount, outputBuilder);
}
var output = TrimTrailingNewLineIfExistsAndRequired(outputBuilder.ToString(), trimTrailingNewLineIfExists);
return output;
}
private static void AddDelimiterIfRequired(StringBuilder outputBuilder, int propertyCount, string delimiter,
int propertyIndex)
{
bool isLastProperty = (propertyIndex + 1 == propertyCount);
if (!isLastProperty)
{
outputBuilder.Append(delimiter);
}
}
private static void AddNewLineIfRequired(bool trimTrailingNewLineIfExists, int itemIndex, int itemCount,
StringBuilder outputBuilder)
{
bool isLastItem = (itemIndex + 1 == itemCount);
if (!isLastItem || !trimTrailingNewLineIfExists)
{
outputBuilder.Append(Environment.NewLine);
}
}
private static void AppendListItemToOutputBuilder<T>(StringBuilder outputBuilder,
T listItem,
PropertyInfo[] properties,
int propertyCount,
string delimiter)
where T : class, new()
{
for (int propertyIndex = 0; propertyIndex < properties.Length; propertyIndex += 1)
{
var property = properties[propertyIndex];
var propertyValue = property.GetValue(listItem);
outputBuilder.Append(propertyValue);
AddDelimiterIfRequired(outputBuilder, propertyCount, delimiter, propertyIndex);
}
}
private static PropertyInfo[] GetPropertiesOfType<T>() where T : class, new()
{
Type itemType = typeof (T);
var properties = itemType.GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public);
return properties;
}
private static string TrimTrailingNewLineIfExistsAndRequired(string output, bool trimTrailingNewLineIfExists)
{
if (!trimTrailingNewLineIfExists || !output.EndsWith(Environment.NewLine)) return output;
int outputLength = output.Length;
int newLineLength = Environment.NewLine.Length;
int startIndex = outputLength - newLineLength;
output = output.Substring(startIndex, newLineLength);
return output;
}
}
}
答案 3 :(得分:0)
将每个字符串数组集合传递给此函数,这将返回CSV格式的字符串,您可以将其保存到大型字符串缓冲区或逐行写入文件。
C#
public string CSVout(string[] strArray)
{
string sOut = "";
foreach (void s_loopVariable in strArray) {
s = s_loopVariable;
if (s.Contains(","))
s = Strings.Chr(34) + s + Strings.Chr(34);
sOut += s + ",";
}
if (Strings.Right(sOut, 1) == ",")
sOut = Strings.Left(@out, @out.Length - 1);
return sOut;
}
VB.NET:
Function CSVout(strArray() As String) As String
Dim out As String = ""
For Each s In strArray
If s.Contains(",") Then s = Chr(34) + s + Chr(34)
out &= s + ","
Next
If Strings.Right(out, 1) = "," Then out = Strings.Left(out, out.Length - 1)
Return out
End Function