C# DataGirdview手动添加数据,导出txt文件并自动对齐

时间:2021-05-12 09:21:23

//DataGirdview手动添加数据

private void btnDataGirdView_Click(object sender,EventArgs e)

{

      dataGridView1.Columns.Add("a","标题1");

      dataGridView1.Columns.Add("b","标题2");

      dataGridView1.Columns.Add("c","标题3");

      string[] dr1= { "1","22","3333" };

      string[] dr2= { "4444","55","6" };

      DataGridViewRow Row=new DataGridViewRow();

      int index=dataGridView1.Rows.Add(Row);

      dataGridView1.Rows[index].Cells[0].Value=dr1[0].ToString();

      dataGridView1.Rows[index].Cells[1].Value=dr1[1].ToString();

      dataGridView1.Rows[index].Cells[2].Value=dr1[2].ToString();

      DataGridViewRow Row2=new DataGridViewRow();

      int index2=dataGridView1.Rows.Add(Row2);

      dataGridView1.Rows[index2].Cells[0].Value=dr2[0];

      dataGridView1.Rows[index2].Cells[1].Value=dr2[1];

      dataGridView1.Rows[index2].Cells[2].Value=dr2[2];  

    }

//DataGirdview导出txt文件,并自动对齐

    private void btnOutPutText_Click(object sender,EventArgs e)

    {

      string FullFileName=@"D:\aaa.txt";

     // FileStream fs=new FileStream(FullFileName,FileMode.CreateNew);

      StreamWriter sw=new StreamWriter(FullFileName,true,Encoding.Default);

      string str="";

      for(int i=0;i<dataGridView1.Rows.Count-1;i++)

      {

        for(int j=0;j<dataGridView1.Columns.Count;j++)

        {

         str=dataGridView1.Rows[i].Cells[j].Value.ToString().Trim();

         if(str.Length<10)

           str=str.PadRight(10,' ');

         str=str+"|";

          sw.Write(str);

        }

        sw.WriteLine("");

      }

      sw.Close();

    }