Fathy Geaiessah

Fathy Geaiessah

  • NA
  • 17
  • 12k

Export datagridview in a windows application to excel in C#

Jun 15 2013 9:45 AM

 I have a code that export a datagridview content in a windows application to excel but it doesn't enable the user to name and locate the created excel file, i want to modify the code to enable the user to name and locate the created excel file using SaveFileDialog, here is the code
button2 in code is the export to excel button,

Note: the application is a windows application, i have posted this question but there is a problem in reply link, and i couldn't continue replying the question.

private void button2_Click(object sender, EventArgs e)

{

Excel.

Application xlApp;

Excel.

Workbook xlWorkBook;

Excel.

Worksheet xlWorksheet;

object misValue = System.Reflection.Missing.Value;

xlApp =

new Excel.ApplicationClass();

xlWorkBook = xlApp.Workbooks.Add(misValue);

xlWorksheet = (Excel.

Worksheet)xlWorkBook.Worksheets.get_Item(1);

int i = 0;

int j = 0;

for (i = 0; i <= dataGridView1.RowCount - 1; i++)

{

for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)

{

DataGridViewCell cell = dataGridView1[j, i];

xlWorksheet.Cells[i+1, j+1] = cell.Value;

}

}

xlWorkBook.SaveAs(

"Products.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

xlWorkBook.Close(

true, misValue, misValue);

xlApp.Quit();

releaseobject(xlWorksheet);

releaseobject(xlWorkBook);

releaseobject(xlApp);

MessageBox.Show("Excel file is created successfully");

}

private void releaseobject(object obj)

{

try

{

System.Runtime.InteropServices.

Marshal.ReleaseComObject(obj);

obj =

null;

}

catch (Exception ex)

{

obj =

null;

MessageBox.Show("Exception Occured while releasing object " + ex.ToString());

}

finally

{

GC.Collect();

}

}


Answers (1)