使用格式将网格中的数据写入文本文件

时间:2014-05-29 11:53:54

标签: c# .net text datagridview outputstream

我在UI(win表单)中有一个DataGridView,现在想要将网格中的数据写入文本文件。

我已尝试使用以下代码。但它没有给出我想要的输出。

public void WriteToTextFile (DataGridView dgv)
        {
            string file_name = "D:\\test1.txt";

        System.IO.StreamWriter objWriter;

        objWriter = new System.IO.StreamWriter(file_name);

        int count = dgv.Rows.Count;
        for (int row = 0; row < count-1; row++)
        {
            int colCount = dgv.Rows[row].Cells.Count; 

            for ( int col = 0; col < colCount-1; col++)  
            {
                objWriter.WriteLine(dgv.Rows[row].Cells[col].Value.ToString());
            }
        // record seperator could be written here.
        }
        objWriter.Close();
        }

输出(仅显示单个项目(一个网格行))

8130201489

D.I.S.Peter

292331pslr

0100507563

Sharpe Eyes Pvt Ltd

A002    

SalaryFeb11  

110228

但是所需的输出是......(不是这应该是一行)

8130201489D.I.S.PETER     2923319SLR0100507563SHARPEYES PVT LTD A002          SALARYFEB11    110228      @

如何修改上述代码才能将其输出?
另外,如果我需要在单词之间添加一些空格,如何插入它?写完后我想将扩展名.txt更改为.dat如何做到这一点。

1 个答案:

答案 0 :(得分:1)

不要用WriteLine()写下每个值。相反,使用StringBuilder构造每一行,然后将整行写为输出:

using System.IO;
using System.Text;   

public void WriteToTextFile (DataGridView dgv)
{
    String file_name = "D:\\test1.txt";
    using (StreamWriter objWriter = new StreamWriter(file_name))
    {
        for (Int32 row = 0; row < dgv.Rows.Count - 1; row++)
        {
            StringBuilder sb = new StringBuilder();
            for (Int32 col = 0; col < dgv.Rows[row].Cells.Count - 1; col++)  
            {
                if (!String.IsNullOrEmpty(sb.ToString()))
                    sb.Append(",");  //any delimiter you choose
                sb.Append(dgv.Rows[row].Cells[col].Value.ToString().ToUpper());
            }
            objWriter.WriteLine(sb.ToString());
        }
    }

    //Rename the file
    File.Move(file_name, Path.ChangeExtension(file_name, "dat"));  //with or without a leading period
}