如何在动态创建的datagridView中显示程序创建的数据表?

时间:2019-01-14 08:48:56

标签: datagridview datatable

我想将datagridview导出为具有选定列的excel。 这段代码仅给出一个空白的.xlsx excel文件。 但是我希望它用选定的列填充“ routine_data_grid” datagridview值。我真的坚持这个问题。如何解决这个问题?任何帮助,我们都感激不尽。

try
        {
            MySqlDataAdapter dp = new MySqlDataAdapter();
            DataTable d = new DataTable();
            d.Columns.Add("Days");
            d.Columns.Add("Groups");
            d.Columns.Add("Room no");                        

            foreach (DataGridViewRow row in routine_data_grid.Rows)
            {
                int i = row.Index;

                DataRow dro = d.NewRow();
                dro["Days"] = routine_data_grid.Rows[i].Cells[1].Value.ToString();
                dro["Groups"] = routine_data_grid.Rows[i].Cells[2].Value.ToString();
                dro["Room no"] = routine_data_grid.Rows[i].Cells[3].Value.ToString();

            }

            DataGridView gv = new DataGridView();


            gv.DataSource = d;


            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
            worksheet = workbook.Sheets["Sheet1"];
            worksheet = workbook.ActiveSheet;
            worksheet.Name = "Routine";
            for (int i = 1; i < gv.Columns.Count+1; i++)
            {
                worksheet.Cells[1, i] = gv.Columns[i - 1].HeaderText;
            }
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                for (int j = 0; j < gv.Columns.Count; j++)
                {


                        worksheet.Cells[i + 2, j + 1] = gv.Rows[i].Cells[j].Value.ToString();



                }
            }
            var saveFileDialoge = new SaveFileDialog();
            saveFileDialoge.FileName = "New Routine";
            saveFileDialoge.DefaultExt = ".xlsx";
            if (saveFileDialoge.ShowDialog() == DialogResult.OK)
            {
                workbook.SaveAs(saveFileDialoge.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            app.Quit();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

1 个答案:

答案 0 :(得分:0)

我已经找到了。我只是将另一个DataGridView用于其他Datatable,而我却保持不可见。那就是我解决问题的方式。