C # Сохранить DataGridView в текстовый файл - PullRequest
1 голос
/ 15 мая 2019

В настоящее время я пытаюсь использовать datagridview в первый раз, мне удалось до сих пор с ним многое сделать (например, импортировать текстовые файлы), однако у меня возникли проблемы при попытке сохранить содержимое datagridview в текстовый файл .

Вывод, который я сейчас получаю:

    0,
 Cat,
 Yes,
10,
20,
30,
40,
50,
1,
 Dog,
 No,
10,
20,
30,
40,
50,

Я хочу, чтобы экспорт выглядел так:

0, Cat, Yes, 10, 20, 30, 40, 50
1, Dog, No, 10, 20, 30, 40, 50
etc.

Это код, который я сейчас использую:

using (TextWriter tw = new StreamWriter("example.txt"))
{
    for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                {
                    for(int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        tw.WriteLine($"{dataGridView1.Rows[i].Cells[j].Value.ToString()},");
                    }
                }
    }

Кто-нибудь здесь может помочь мне с этим вопросом? Спасибо!

Ответы [ 3 ]

4 голосов
/ 15 мая 2019

Попробуйте следующие изменения tw.Write() insted of tw.WriteLine():

using (TextWriter tw = new StreamWriter("example.txt"))
{
    for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    {
         for(int j = 0; j < dataGridView1.Columns.Count; j++)
         {
             tw.Write($"{dataGridView1.Rows[i].Cells[j].Value.ToString()}");

             if(!j == dataGridView1.Columns.Count - 1)
             {
                tw.Write(",");
             }
         }
         tw.WriteLine();
     }
}
1 голос
/ 15 мая 2019

Используйте tw.Write () вместо tw.WriteLine () до тех пор, пока не закончите со всеми столбцами строки, кроме последнего, а затем tw.WriteLine () для данных последнего столбца, чтобы завершить строку.

0 голосов
/ 11 июня 2019

Итак, DGV в текстовый файл? Вот как я это делаю.

private void button1_Click(object sender, EventArgs e)
        {
            //This line of code creates a text file for the data export.
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\your_path_here\\sample.txt");
            try
            {
                string sLine = "";

                //This for loop loops through each row in the table
                for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
                {
                    //This for loop loops through each column, and the row number
                    //is passed from the for loop above.
                    for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
                    {
                        sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
                        if (c != dataGridView1.Columns.Count - 1)
                        {
                            //A comma is added as a text delimiter in order
                            //to separate each field in the text file.
                            //You can choose another character as a delimiter.
                            sLine = sLine + ",";
                        }
                    }
                    //The exported text is written to the text file, one line at a time.
                    file.WriteLine(sLine);
                    sLine = "";
                }

                file.Close();
                System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception err)
            {
                System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                file.Close();
            }
        }
...