【问题标题】:Export selected rows datagridview to excel将选定的行datagridview导出到excel
【发布时间】:2013-10-14 20:27:11
【问题描述】:

我必须拿出一个程序来导出选定的行 datagridview 以使用相应的标题进行 excel。我已经完成了将整个 datagridview 导出到 excel,但现在我只想使用选定的行来完成。我该怎么做?

这是我将整个 datagridview 导出到 excel 的代码

private void GenerateExcel(DataTable table3, string excelSheetName) {

        string fileName = "TestingofDSI";
        //string currentDirectorypath = "C:\testingdsi";
        string currentDirectorypath = Environment.CurrentDirectory;
        string finalFileNameWithPath = string.Empty;

        fileName = string.Format("{0}_{1}", fileName, DateTime.Now.ToString("dd-MM-yyyy"));
        finalFileNameWithPath = string.Format("{0}\\{1}.xlsx", currentDirectorypath, fileName);


        var newFile = new FileInfo(finalFileNameWithPath);


        using (var package = new ExcelPackage(newFile))
        {

            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(excelSheetName);


            if (table != null)
            {

                worksheet.Cells["A1"].LoadFromDataTable(table3, true, OfficeOpenXml.Table.TableStyles.Medium2);
                //worksheet.Cells["A1"].LoadFromDataTable(table, true, TableStyles.None);


                /*  package.Workbook.Properties.Title = @"This code is part of tutorials available at http://bytesofcode.hubpages.com";
                  package.Workbook.Properties.Author = "Bytes Of Code";
                  package.Workbook.Properties.Subject = @"Register here for more http://hubpages.com/_bytes/user/new/";*/


                package.Save();

                MessageBox.Show(string.Format("File name '{0}' generated successfully.", fileName)
                    , "File generated successfully!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {

                MessageBox.Show("please load data from database!");

   }


        }
    }

//绑定数据的代码

   private void loadButton_Click(object sender, EventArgs e)
    {
             GetData(" select * from jacksonpc.product;");
            dataGridView1.DataSource = bindingSource1;
     }

    private void GetData(string selectCommand)
      {
        try
        {
            // Specify a connection string. Replace the given value with a 
            // valid connection string for a Northwind SQL Server sample
            // database accessible to your system.
            String connectionString = "datasource=localhost;port=3306;username=root;password=1234";

            // Create a new data adapter based on the specified query.
            dataAdapter = new MySqlDataAdapter(selectCommand, connectionString);

            // Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand. These are used to
            // update the database.
            MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);

            // Populate a new data table and bind it to the BindingSource.
            table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(table);
            bindingSource1.DataSource = table;



            /* table2 = new DataTable();
             table2.Locale = System.Globalization.CultureInfo.InvariantCulture;
             dataAdapter.Fill(table2);
             bindingSource2.DataSource = table2;
             // Resize the DataGridView columns to fit the newly loaded content.*/

                        dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
     }

【问题讨论】:

  • 您是否添加了任何复选框来选择行?
  • @Arshad 我必须这样做吗?还有其他替代方法吗?
  • 如果用户想要选择多行,你将如何识别选定的行
  • 你想使用单行吗
  • @Arshad 我可以通过单击其中一个按钮来识别它,它将突出显示整行。我想处理不止一行。

标签: c# visual-studio-2010 excel datagridview export-to-excel


【解决方案1】:

您可以在构造函数或Form_Load 中更改datagridview SelectionMode 属性

dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
然后用户将能够在CTRLShift 的帮助下选择多行 在您的打印方法上,您必须创建一个带有选定行的DataTable

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    //Create a DataTable with same column name
    //fill each column like row.Cells[1].Value.ToString();              

}

【讨论】:

  • 这将如何将选定的行导出到excel?我可以选择多个但不能将它们提取到 excel 中..
  • 首先您必须创建一个数据表,然后创建新行,将新行添加到数据表...
  • 之后通过传递新创建的数据表调用你的 print()
  • 感谢您的帮助,我现在可以做到,但我现在有新问题...我可以通过您的电子邮件或其他方式向您发送屏幕截图吗?
  • 你只能在这里讨论。在问题中附上详细信息
猜你喜欢
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 2013-09-11
  • 2011-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多