如何在DataGridView中导出具有相同类别的行中的txt文件?

时间:2016-03-01 04:22:50

标签: c# datagridview export

我需要导出每行一个文件的所有网格,但如果它们具有相同的类别,则导出同一个txt文件中的每一行,如果在所有网格中只有一个文件,例如类别8,那么row将是一个txt文件。

enter image description here

1 个答案:

答案 0 :(得分:1)

我假设您要为每个类别组创建不同的文本文件。 试试这个:

  private void SaveToTextFIle()
    {
        //get all distinct categories
        DataView view = new DataView((DataTable)dataGridView1.DataSource);
        DataTable distinctValues = view.ToTable(true, "CategoryID");

        //save each category
        foreach (DataRow categoryRow in distinctValues.Rows)
        {
            var sb = new StringBuilder();

            //if you want headers
            var headers = dataGridView1.Columns.Cast<DataGridViewColumn>();
            sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));

            //form actual data available for this category
            foreach (DataGridViewRow row in dataGridView1.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["CategoryID"].Value.ToString() == categoryRow["CategoryID"].ToString()))
            {
                var cells = row.Cells.Cast<DataGridViewCell>();
                sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
            }

            //write to file
            File.WriteAllText(@"D:\" + categoryRow["CategoryID"] + ".txt", sb.ToString());
         }
    }