简体   繁体   English

C# 将 DataGridView 保存到文本文件

[英]C# Save DataGridView to Text File

I'm currently attempting to use datagridview for the first time, I have managed to do many things with it so far (such as importing text files) however, I have trouble when attempting to save the datagridview's contents to a text file.我目前正在尝试第一次使用 datagridview,到目前为止我已经设法用它做很多事情(例如导入文本文件),但是,我在尝试将 datagridview 的内容保存到文本文件时遇到了麻烦。

The output I'm currently getting is:我目前得到的输出是:

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

I want the export to look like this:我希望导出看起来像这样:

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

This is the code I'm currently using:这是我目前使用的代码:

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

Anyone here able to help me with this issue?这里有人能帮我解决这个问题吗? Thank you!谢谢!

Try the following changes tw.Write() insted of 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();
     }
}

So, DGV to Text file?那么,DGV 到文本文件? This is how I do it.我就是这样做的。

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

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

您如何将其重新加载到数据网格中?

I don't work in C#, but often use these forums as a reference.我不使用 C#,但经常使用这些论坛作为参考。 I develop interfaces for industrial applications.我为工业应用开发接口。 Anyway, the simplest way to do this is through the clipboard.无论如何,最简单的方法是通过剪贴板。 Use the SelectAll() method on your DGV, Throw that DGV data into the Clipboard with the Clipboard.SetDataObject() method, use the File.WriteAllText(), and Clipboard.GetText() methods to write the clipboard text to a file.在 DGV 上使用 SelectAll() 方法,使用 Clipboard.SetDataObject() 方法将该 DGV 数据放入剪贴板,使用 File.WriteAllText() 和 Clipboard.GetText() 方法将剪贴板文本写入文件。 My code is below.我的代码如下。 You will notice I have to write out everything from it's namespace so I apologize for it not being exactly how C# is.你会注意到我必须写出它的命名空间中的所有内容,所以我为它不是 C# 的方式而道歉。 Note: If you want to make a csv file, DGVs view cell breaks as horizontal tabs (ascii 9).注意:如果要制作 csv 文件,DGV 会将单元格拆分为水平选项卡 (ascii 9)。 You can do a replace() method for commas.您可以为逗号执行 replace() 方法。 Note: DGV.ClearSelection() is a nice way to finish it off.注意:DGV.ClearSelection() 是完成它的好方法。 Note: you may have to enable ClipboardCopyMode on your DGV.注意:您可能必须在 DGV 上启用 ClipboardCopyMode。

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

With the following code you can save and restore the content of every dataGridView .使用以下代码,您可以保存和恢复每个 dataGridView 的内容

How to do it:怎么做:

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);
}

Helper functions:辅助功能:

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];
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM