【问题标题】:C# Save DataGridView to Text FileC# 将 DataGridView 保存到文本文件
【发布时间】:2019-05-14 21:07:24
【问题描述】:

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

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

【问题讨论】:

  • WriteLine更改为Write并在ToString()之后添加对Trim()的调用

标签: c# datagridview export text-files export-to-text


【解决方案1】:

尝试以下更改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();
     }
}

【讨论】:

  • 这很好用,但是我在每行的末尾都有一个逗号:0, Cat, Yes, 10, 20, 30, 40, 50, 1, Dog, No, 10, 20, 30, 40, 50, 有没有办法删除那些结尾的?干杯!
  • 我已对我的答案进行了更改。请测试它并告诉我。
  • 遗憾的是它没有用,逗号仍然出现在末尾。我还必须将if(!j == dataGridView1.Columns.Count) 更改为if(j != dataGridView1.Columns.Count)
  • 啊抱歉应该是if(!j == dataGridView1.Columns.Count - 1)
【解决方案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();
            }
        }

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      我不使用 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());
      

      【讨论】:

      • 是的,它可以保存数据,但以后似乎无法以相同的方式恢复它。
      【解决方案5】:

      使用以下代码,您可以保存和恢复每个 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];
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-27
        • 2013-04-07
        • 1970-01-01
        相关资源
        最近更新 更多