使用streamwriter将GridView导出为CSV文件

时间:2011-12-04 01:45:00

标签: c# visual-studio-2010 csv datagridview

我正在写一个程序而且卡住了。我希望能够在打开的程序中编辑数据网格,然后单击按钮以保存和更新数据网格填充的CSV文件。

我知道这是可能的,但需要帮助我如何使用我的代码:

       private void GridView(List<string[]> parsedData)
        {
            dataGridView1.Rows.Clear();
            dataGridView1.ColumnCount = 2;
            for (int i = 0; i < 2; i++)
            {
                var sb = new StringBuilder(parsedData[0][i]);
                sb.Replace('_', ' ');
                sb.Replace("\"", "");
                dataGridView1.Columns[i].Name = sb.ToString();
            }

            foreach (string[] row in parsedData)
            {
                dataGridView1.Rows.Add(row);
            }

            dataGridView1.Rows.Remove(dataGridView1.Rows[0]);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            List<string[]> parsedData = read(@"c:\users\dick\documents\visual studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\file.csv", ',');

            GridView(parsedData);

        }



        private void button3_Click(object sender, EventArgs e)
        {
            List<string[]> parsedData = read(@"c:\users\dick\documents\visual studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Alteredfile.csv", ';');

            GridView(parsedData);

        }



        private void button2_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < dataGridView1.Columns.Count; k++)
            {
                sb.Append(dataGridView1.Columns[k].HeaderText + ',');
            }
            sb.Append("\r\n");
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int K = 0; K < dataGridView1.Columns.Count; K++)
                {
                    sb.Append(dataGridView1.Rows[i].Cells[K].ErrorText + ',');
                }
                sb.Append("\r\n");
            }

            using (var sw = new StreamWriter(@"c:\users\dick\documents\visual studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Alteredfile.csv"))
            {
                sw.WriteLine(sb.ToString());
    }

    }}
}

1 个答案:

答案 0 :(得分:0)

我现在无法尝试,但这条线路错了:

 sb.Append(dataGridView1.Columns[k].HeaderText + ',');

你应该做这样的事情来获取网格的字符串:

(string)dataGridView1.Rows[x].Columns[k].value

(string[])dataGridView1.Rows[x].value