Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I worked with several methods but they all export datagridview I just want the line that will be selected
thank you in advance

What I have tried:

i tried this code but Allows to export all datagridview lines but I want to export just the line that will be selected
using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using System.Windows.Forms;  
  
namespace CSharpCornerDemo  
{  
    public partial class Form3 : Form  
    {  
        public Form3()  
        {  
            InitializeComponent();  
        }  
  
        private void button1_Click(object sender, EventArgs e)  
        {  
            myDataGridView.Columns.Clear();  
  
            myDataGridView.ColumnCount = 2;  
            myDataGridView.Columns[0].Name = "User ID";  
            myDataGridView.Columns[1].Name = "Password";  
  
            string[] row = new string[] { "abc", "abc" };  
            myDataGridView.Rows.Add(row);  
            row = new string[] { "pqr", "pqr" };  
            myDataGridView.Rows.Add(row);  
            row = new string[] { "ghanashyam", "ghanashyam" };  
            myDataGridView.Rows.Add(row);  
            row = new string[] { "jignesh", "jignesh" };  
            myDataGridView.Rows.Add(row);  
  
            DataGridViewLinkColumn dgvLink = new DataGridViewLinkColumn();  
            dgvLink.UseColumnTextForLinkValue = true;  
            dgvLink.LinkBehavior = LinkBehavior.SystemDefault;  
            dgvLink.HeaderText = "Link Data";  
            dgvLink.Name = "SiteName";  
            dgvLink.LinkColor = Color.Blue;  
            dgvLink.TrackVisitedState = true;  
            dgvLink.Text = "http://www.c-sharpcorner.com";  
            dgvLink.UseColumnTextForLinkValue = true;  
  
            myDataGridView.Columns.Add(dgvLink);  
        }  
  
        private void myDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)  
        {  
  
            string UserId = myDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString();  
            string Password = myDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString();  
            // 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 < myDataGridView.Columns.Count + 1; i++)  
            {  
  
                worksheet.Cells[1, i] = myDataGridView.Columns[i - 1].HeaderText;  
  
            }  
  
  
            // storing Each row and column value to excel sheet  
  
             
                for (int j = 0; j < myDataGridView.Columns.Count; j++)  
                {  
  
                    worksheet.Cells[0, j + 1] = myDataGridView.Rows[0].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();  
  
        }  
    }  
}  
Posted
Updated 18-Aug-17 8:14am
v2

I would suggest add a button, click and export the selected row.

C#
private void btnExport_Click(object sender, EventArgs e)
        {
            if (myDataGridView.SelectedRows.Count != 0)
            {
                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";

                DataGridViewRow row = this.myDataGridView.SelectedRows[0];
                //row.Cells["ColumnName"].Value;

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

                int rowIndex = 2;
                foreach (DataGridViewRow r in myDataGridView.SelectedRows)
                {
                    for (int j = 0; j < r.Cells.Count; j++)
                    {
                        worksheet.Cells[rowIndex, j + 1] = r.Cells[j].Value.ToString();
                    }

                    rowIndex++;
                }

                workbook.SaveAs("c:\\temp\\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();
            }
 
Share this answer
 
Comments
Member 13055644 15-Mar-17 12:24pm    
THANK YOU I WILL TRY THIS CODE
Member 13055644 15-Mar-17 12:31pm    
WHEN I execute they posted this error

Index non valide. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
Bryian Tan 15-Mar-17 12:43pm    
which line throwing that error because I'm not getting that error at my end.
Member 13055644 15-Mar-17 13:43pm    
in this line


worksheet = workbook.Sheets["Sheet1"];
Bryian Tan 15-Mar-17 14:08pm    
Odd. Because that what you have originally. The changes I proposed are, add a button, use the same code + the below modification. I'm glad other solution work for you.
if (myDataGridView.SelectedRows.Count != 0)

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

                int rowIndex = 2;
                foreach (DataGridViewRow r in myDataGridView.SelectedRows)
                {
                    for (int j = 0; j < r.Cells.Count; j++)
                    {
                        worksheet.Cells[rowIndex, j + 1] = r.Cells[j].Value.ToString();
                    }

                    rowIndex++;
                }
 
Share this answer
 
Comments
Member 13055644 15-Mar-17 10:37am    
I know how to select a line in the datagridview but I want to export the line selected in excel how to do please
Graeme_Grant 15-Mar-17 10:40am    
you already have the code then. Look for this:
for (int i = 1; i < myDataGridView.Columns.Count + 1; i++)  
{  
    worksheet.Cells[1, i] = myDataGridView.Columns[i - 1].HeaderText;  
}
Member 13055644 15-Mar-17 10:43am    
This code is already written in the script I posted but it does not allow to export the selected line
Graeme_Grant 15-Mar-17 20:39pm    
I was not in a position to fire up VS and build a sample project for you. Anyhow, you already had the code to do it, and figured seeing as you "know how to select a line in the DataGridView ", the rest would be easy for you.

Glad to see that you have it solved.
You really need to carefully read the solution on the link that @Graeme_Grant gave you. It clearly shows that you need to look at the SelectedRows property.
Example using your code:
C#
          // storing header part in Excel  
for (var i = 0; i < dataGridView1.Columns.Count; i++)
    worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;


// storing Each row and column value to excel sheet  
for (var i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
    for (var j = 0; j < dataGridView1.Columns.Count; j++)
    {
        if (dataGridView1.Rows[i].Cells[j].Value == null) continue;
        worksheet.Cells[2 + i, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
    }
}

As an aside - I wouldn't have put this in a generalised CellContentClick event - it means that you will struggle to select more than one row. If you intend to have a button that says "export this row" then you need to check that you are clicking in the correct column before diving straight into creating a spreadsheet.
 
Share this answer
 
v2
C#
<pre> int cr = 1;
            int cc = 1;
           
            //Loop through each row and read value from each column. 
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {

                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    // Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check. 
                    if (cr == 1)
                    {
                        xlWorkSheet.Cells[cr, cc] = dataGridView1.Columns[j].HeaderText;
                    }

                    cc++;
                }
                cc = 1;
                cr++;


            } 
            //get data:
            //you can erase this if you dont need data from rows:
            for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
            {
                for (int j = 0; j <dataGridView1.Columns.Count; j++)
                {
                    DataGridViewCell cell = dataGridView1[j, i];
                    xlWorkSheet.Cells[i + 2, j + 1] = cell.Value;
                    
                }
            }
 
Share this answer
 
Comments
Richard Deeming 18-Aug-17 14:26pm    
Do not post your question as a "solution" to someone else's questions!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900