如何仅将数据网格视图中选定的行导出到excel中

本文关键字:excel 数据 数据网 网格 视图 何仅 | 更新日期: 2023-09-27 18:21:18

如何将dgv中的选定行导出到excel中?下面是我导入excel并查找值的代码。

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {               
            //this.textBox1.Text = openFileDialog1.FileName;

            //string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox1.Text + ";Extended Properties='"Excel 8.0;HDR=Yes:'";";
            String PathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties='"Excel 12.0 XML;HDR=Yes:'";";                        
            OleDbConnection conn = new OleDbConnection(PathConn);
            OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [sheet1$]", conn);
            DataTable dt = new DataTable();
            myDataAdapter.Fill(dt);
            dataGridView1.DataSource = dt;
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        dataGridView1.ClearSelection();
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        try
        {          
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells["Name"].Value.ToString().ToUpperInvariant().Contains(textBox1.Text.ToUpperInvariant()))
                {
                    dataGridView1.Rows[row.Index].Selected = true;                        
                }
            }
        }
        catch (Exception)
        {
        }
    }

如何仅将数据网格视图中选定的行导出到excel中

我想你知道如何将DataTable导出到excel(你可以使用现有的库,如Aspose Cells或使用Interop),所以我只编写创建该DataTable的代码:

private DataTable CreateDataTableFromSelectedRows()
{
    var dtToExport = new DataTable();
    foreach(DataGridViewRow row in dataGridView1.SelectedRows)
    {
        var dr = row.DataBoundItem as DataRow;
        dtToExport.ImportRow(dr);
    }
    return dtToExport;
}

如果你使用Aspose细胞,它就会变成:

private void btnExportSelectedRows(object sender, EventArgs e)
{
        string filePath = "C:''test.xlsx";
        Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook();
        wb.FileFormat = Aspose.Cells.FileFormatType.Xlsx;
        Worksheet sheet = wb.Worksheets[0];
        DataTable dt = CreateDataTableFromSelectedRows();
        sheet.Cells.ImportDataTable(dt, true, "A1");
        wb.Save(filePath);
}

但通过使用导出代码,您提供的一切都变成了:(为了简洁起见,我删除了对代码的现有评论)

private void button1_Click_1(object sender, EventArgs e) 
{
    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;                   
    app.Visible = true;
    worksheet = workbook.Sheets["Sheet1"];
    worksheet = workbook.ActiveSheet;
    worksheet.Name = "Exported from gridview";
    for(int i=1;i<dataGridView1.Columns.Count+1;i++)
    {
         worksheet.Cells[1, i] = dataGridView1.Columns[i-1].HeaderText;
    }
    // It's the part which we are interested in
    // we just need to change dataGridView1.Rows to dataGridView1.SelectedRows
    for (int i=0; i < dataGridView1.SelectedRows.Count ; i++)
    {
        for(int j=0;j<dataGridView1.Columns.Count;j++)
        {
            worksheet.Cells[i + 2, j + 1] = dataGridView1.SelectedRows[i].Cells[j].Value.ToString();
        }
    }
    workbook.SaveAs("c:''output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  app.Quit();
}

我想它会起作用的。

请参阅以下导出到Excel的代码:

private void button1_Click_1(object sender, EventArgs e)
    {
        // creating Excel Application
        Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();

        // creating new WorkBook within Excel application
        Microsoft.Office.Interop.Excel._Workbook workbook =  app.Workbooks.Add(Type.Missing);

        // creating new Excelsheet in workbook
         Microsoft.Office.Interop.Excel._Worksheet worksheet = null;                   
       // see the excel sheet behind the program
        app.Visible = true;
       // get the reference of first sheet. By default its name is Sheet1.
       // store its reference to worksheet
        worksheet = workbook.Sheets["Sheet1"];
        worksheet = workbook.ActiveSheet;
        // changing the name of active sheet
        worksheet.Name = "Exported from gridview";

        // storing header part in Excel
        for(int i=1;i<dataGridView1.Columns.Count+1;i++)
        {
            worksheet.Cells[1, i] = dataGridView1.Columns[i-1].HeaderText;
        }

        // storing Each row and column value to Excel sheet
        for (int i=0; i < dataGridView1.Rows.Count-1 ; i++)
        {
            for(int j=0;j<dataGridView1.Columns.Count;j++)
            {
                worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
            }
        }

        // save the application
        workbook.SaveAs("c:''output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        // Exit from the application
        app.Quit();
    }