我正在尝试开发一个应用程序,它将从数据网格中获取数据并基于下拉菜单选项返回仅包含所选客户端的csv文件。我的代码如下所示,这链接到我发布的上一个问题,但我仍然没有得到任何价值,我真的需要对此进行排序,所以我想知道是否有人可以看到我出错或者提供替代方案
//Master inventory export
private void ExportClass_Click(object sender, EventArgs e)
{
StringBuilder str = new StringBuilder();
objSqlCommands2 = new SqlCommands("MasterInventory", "ClientName");
string strString = str.ToString();
string Filepath = txtSaveShareClass.Text.ToString();
str.Append("ISIN ,FundName,Status,Share CCY,Benchmark,NAV Freq,CLASSCODE,SIMULATION,HEDGED,FUNDCCY");
StringManipulation sm = new StringManipulation();
foreach (DataRow dr in this.CalcDataSet.MasterInventory)
{
foreach (object field in dr.ItemArray)
{
str.Append(field.ToString() + ",");
}
str.Replace(",", "\n", str.Length - 1, 1);
}
try
{
System.IO.File.WriteAllText(Filepath, str.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Write Error :" + ex.Message);
}
List<string[]> lsClientList = objStringManipulation.parseCSV(Filepath,cmbClientList .Text.ToCharArray());
foreach (string[] laClient in lsClientList)
{
sm.parseCSV2(Filepath, cmbClientList.Text.ToCharArray());
List<string[]> newFoo = lsClientList.Where(x => x.Contains(cmbClientList.Text)).ToList();
List<string[]> Results = sm.parseCSV2(Filepath, cmbClientList.Text.ToCharArray()).Where(x => x.Contains(cmbClientList.Text)).ToList();
//Refreshs the Client table on display from the
System.IO.File.WriteAllText(Filepath, Results.ToString());
}
this.TableAdapter.Fill(this.CalcDataSet.MasterInventory);
dataGridView2.Update();
}
答案 0 :(得分:1)
如果您的所有变量都填写正确且Results
列表中包含您期望的数据,则问题出在WriteAllText
调用上。你有:
System.IO.File.WriteAllText(Filepath, Results.ToString());
这不会产生你似乎期望的输出。它可能只会给你一个班级名称。
Results
是List<string[]>
。如果要将其输出为CSV,则必须枚举它:
using (var outfile = new StreamWriter(Filepath))
{
foreach (var line in Results)
{
StringBuilder sb = new StringBuilder();
foreach (var field in line)
{
sb.Append(field + ",");
}
sb.Length = sb.Length -1;
outfile.WriteLine(sb.ToString());
}
}