C# 将 DataGridView 保存到文本文件

C# Save DataGridView to Text File

我目前是第一次尝试使用 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()},");
                    }
                }
    }

这里有人能帮我解决这个问题吗?谢谢!

使用 tw.Write() 而不是 tw.WriteLine() 直到您完成除该行的最后一列以外的所有内容,然后您在最后一列上使用 tw.WriteLine()行结束的列数据。

尝试以下更改 tw.Write() 代替 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();
     }
}

所以,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();
            }
        }

我不从事 C# 工作,但经常使用这些论坛作为参考。我为工业应用程序开发接口。无论如何,最简单的方法是通过剪贴板。在 DGV 上使用 SelectAll() 方法,使用 Clipboard.SetDataObject() 方法将 DGV 数据放入剪贴板,使用 File.WriteAllText() 和 Clipboard.GetText() 方法编写剪贴板文本到文件。我的代码如下。你会注意到我必须写出它的命名空间中的所有内容,所以我为它与 C# 不完全一样而道歉。注意:如果您想制作 csv 文件,DGV 将单元格分隔符视为水平制表符 (ascii 9)。您可以为逗号执行 replace() 方法。注意:DGV.ClearSelection() 是结束它的好方法。注意:您可能需要在 DGV 上启用 ClipboardCopyMode。

DataGridView1.SelectAll();
System.Windows.Forms.Clipboard.SetDataObject(DataGridView1.GetClipboardContent());
System.IO.File.WriteAllText("File.txt",System.Windows.Forms.Clipboard.GetText());

使用以下代码,您可以保存和恢复每个 dataGridView 的内容

怎么做:

string sContent = "";
private void btnSaveDataGridViewContent_Click(object sender, EventArgs e)
{
    sContent = ReadStringFromDataGridView(ref dataGridView1);
    [Write sContent to File/Database/Whatever]
}

private void btnRestoreDataGridViewContent_Click(object sender, EventArgs e)
{
    [Read sContent from File/Database/Whatever]
    WriteStringToDataGridView(ref dataGridView1, sContent);
}

辅助函数:

string ReadStringFromDataGridView(ref DataGridView MyDataGridView)
{
    string sContent = "";
    for (int row = 0; row<MyDataGridView.RowCount; row++)
    {
        if (row > 0) sContent += "\r";
        for (int col = 0; col<MyDataGridView.ColumnCount; col++)
        {
            if (col > 0) sContent += ";";
            sContent += MyDataGridView[col, row].Value;
        }
    }
    return sContent;
}

void WriteStringToDataGridView(ref DataGridView MyDataGridView, string sContent)
{
    MyDataGridView.Rows.Clear();
    string[] Rows = sContent.Split("\r".ToCharArray());
    for (int row=0; row<Rows.Length; row++)
    {
        MyDataGridView.RowCount = Rows.Length;
        string[] Cols = Rows[row].Split(";".ToCharArray());
        for (int col=0; col<Cols.Length; col++)
        {
            MyDataGridView[col, row].Value = Cols[col];
        }
    }
}