大家好我想把随机双重写入csv文件,因为现在我正在插入字符串,这就是我已经完成的工作。如何改变我的代码以便编写双打字符串非常感谢提前
public class CsvRow : List<string>
{
public string LineText { get; set; }
}
/// <summary>
/// Class to write data to a CSV file
/// </summary>
public class CsvFileWriter : StreamWriter
{
public CsvFileWriter(Stream stream)
: base(stream)
{
}
public CsvFileWriter(string filename)
: base(filename)
{
}
/// <summary>
/// Writes a single row to a CSV file.
/// </summary>
/// <param name="row">The row to be written</param>
public void WriteRow(CsvRow row)
{
StringBuilder builder = new StringBuilder();
bool firstColumn = true;
foreach (string value in row)
{
// Add separator if this isn't the first value
if (!firstColumn)
builder.Append(',');
// Implement special handling for values that contain comma or quote
// Enclose in quotes and double up any double quotes
if (value.IndexOfAny(new char[] { '"', ',' }) != -1)
builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
else
builder.Append(value);
firstColumn = false;
}
row.LineText = builder.ToString();
WriteLine(row.LineText);
}
} static void WriteTest()
{
// Write sample data to CSV file
using (CsvFileWriter writer = new CsvFileWriter("D://WriteTest.csv")) CsvRow rowCol = new CsvRow();
for (int j = 0; j < nbrCol; j++)
rowCol.Add("Col" +j);
writer.WriteRow(rowCol);
{
for (int i = 0; i < 100; i++)
{
CsvRow row = new CsvRow();
for (int j = 0; j < 5; j++)
row.Add(String.Format("Column{0}", j));
writer.WriteRow(row);
}
}
}
答案 0 :(得分:2)
就是这样:
static void WriteTest()
{
// Write sample data to CSV file
using (CsvFileWriter writer = new CsvFileWriter(@"E:\SharedDoc1\WriteTest.csv"))
{
Random rnd = new Random();
for (int i = 0; i < 100; i++)
{
CsvRow row = new CsvRow();
for (int j = 0; j < 5; j++)
row.Add(rnd.NextDouble().ToString("0.000000")); //round to 6 decimal digits
writer.WriteRow(row);
}
}
}
输出如下:
0.848731,0.525468,0.829536,0.397083,0.493102 0.398665,0.914157,0.768229,0.520031,0.249966 0.083535,0.409240,0.325824,0.177057,0.114989
请注意,rnd.NextDouble()
会返回介于0和1之间的双精度数,如果您想要更大的数字,则应将其与您的因子相乘。例如,如果你想要双倍达到1000,请执行以下操作:
row.Add((rnd.NextDouble() * 1000).ToString("0.0#####"));