1
Answer

Export DataGridView content to Excel

Fathy Geaiessah

Fathy Geaiessah

11y
1.4k
1

I have a code that export a datagridview content 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

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)