1

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

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

4

5 回答 5

8

尝试以下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();
     }
}
于 2019-05-14T21:19:08.830 回答
2

那么,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();
            }
        }
于 2019-06-11T02:46:17.503 回答
1

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

于 2019-05-14T21:17:35.977 回答
0

我不在 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());
于 2021-05-17T17:47:00.443 回答
0

使用以下代码,您可以保存和恢复每个 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];
        }
    }
}
于 2021-08-31T05:18:18.880 回答