Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Need help on exporting only visible DataGridView columns to excel, I have this code for hiding columns in DataGridView. this.dg1.Columns[0].Visible = false; And then I have button click event for exporting to excel.

// 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 = "PIN korisnici";

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

but I want to export only visible columns, while I get all of them, anyone, help on this.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Just build a list of visible columns and then export only those, e.g.

List<DataGridViewColumn> listVisible = new List<DataGridViewColumn>();
foreach( DataGridViewColumn col in dg1.Columns )
{
    if (col.Visible)
         listVisible.Add(col);
}

then when you iterate through the columns use your 'visible' list, e.g.

for (int i = 0; i < listVisible.Count; i++)
{
    worksheet.Cells[1, i + 1] = listVisible[i].HeaderText;
}

for (int i = 0; i < dg1.Rows.Count - 1; i++)
{
    for (int j = 0; j < listVisible.Count; j++)
    {
        worksheet.Cells[i + 2, j + 1] = dg1.Rows[i].Cells[listVisible[j].Name].Value.ToString();
    }
}
share|improve this answer
    
you are right.....thank you very much... –  Suresh E Jun 25 '13 at 9:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.