簡體   English   中英

將選定的行datagridview導出到excel

[英]Export selected rows datagridview to excel

我必須拿出一個程序來導出選定的行datagridview以與相應的標頭優秀。 我已經將整個datagridview導出到excel,但是現在我只想選擇行就可以了。 我該怎么做?

這是我將整個datagridview導出到excel的代碼

私人void GenerateExcel(DataTable table3,字符串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);
        }
     }

您可以在構造函數或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();              

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM