c#wpf datagrid将特定的列导出到文本文件

时间:2018-08-09 10:18:45

标签: c# wpf file text

我正在使用一个小型应用程序,用户可以在其中将datagrid内容写入文本文件。 我使用下面的这段代码将数据从SQL获取到数据网格

      SqlConnection con = new SqlConnection("Server = localhost;Database = 
      autoser; Integrated Security = true");
      SqlCommand cmd = new SqlCommand("selectproduct", con); // Using a Store 
      Procedure.
     cmd.CommandType = CommandType.StoredProcedure;
      DataTable dt = new DataTable("dtList");
      cmd.Parameters.AddWithValue("@Code", txtbarcode.Text);

      SqlDataAdapter da = new SqlDataAdapter(cmd);
      da.Fill(dt);
      data.ItemsSource = dt.DefaultView;
      SqlDataAdapter adapt = new SqlDataAdapter(cmd);
      DataSet ds = new DataSet();
      adapt.Fill(ds);
      con.Close();
      int count = ds.Tables[0].Rows.Count;
      if (count == 0)
     {
        MessageBox.Show("This product doesn't excist");
        SystemSounds.Hand.Play();
      }
   else if (count == 1)
     {
       lblinfo.Visibility = Visibility.Visible;
       SystemSounds.Asterisk.Play();

     }

这是我用来将数据网格数据写入文本文件的代码

    public static void WriteDataToFile(DataTable submittedDataTable, string submittedFilePath)
    {
        int i = 0;
        StreamWriter sw = null;

        sw = new StreamWriter(submittedFilePath, false);

        for (i = 0; i < submittedDataTable.Columns.Count - 1; i++)
        {

            sw.Write(submittedDataTable.Columns[i].ColumnName + ";");

        }
        sw.Write(submittedDataTable.Columns[i].ColumnName);
        sw.WriteLine();

        foreach (DataRow row in submittedDataTable.Rows)
        {
            object[] array = row.ItemArray;

            for (i = 0; i < array.Length - 1; i++)
            {
                sw.Write(array[i].ToString() + ";");
            }
            sw.Write(array[i].ToString());
            sw.WriteLine();

        }

        sw.Close();
    }

但是当我使用此代码时,所有列均写入文本文件。我的问题是,在哪里可以更新代码以仅写特定列(不是所有列)

1 个答案:

答案 0 :(得分:0)

请尝试以下更改:

        public static void WriteDataToFile(DataTable submittedDataTable, string submittedFilePath)
        {
            string[] columnNames = { "Column A", "Column B", "Column C", "Column D" };
            int[] columnIndexes = submittedDataTable.Columns.Cast<DataColumn>().Where(x => columnNames.Contains(x.ColumnName)).Select(x => x.Ordinal).ToArray();

            int i = 0;
            StreamWriter sw = null;

            sw = new StreamWriter(submittedFilePath, false);

            sw.WriteLine(string.Join(";", columnNames));

            foreach (DataRow row in submittedDataTable.Rows)
            {
                object[] array = row.ItemArray;

                string[] values = columnIndexes.Select(x => array[x].ToString()).ToArray();
                string csv = string.Join(";", values);

                sw.WriteLine(csv);
            }

            sw.Close();
        }