导出GridView到CSV文件使用流写入器

本文关键字:GridView CSV 文件 导出 | 更新日期: 2023-09-27 18:16:54

我正在写一个程序,被卡住了。我希望能够在打开的程序中编辑数据网格,并单击按钮保存和更新数据网格填充的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());
    }
    }}
}

导出GridView到CSV文件使用流写入器

我现在不能尝试,但是这一行是错误的:

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

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

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

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