export datagridview to excel

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • artteam
    New Member
    • Feb 2007
    • 18

    export datagridview to excel

    Hi All,

    I try to export the table in DataGridView control on my form to MS excel with the following code.

    private void fnExtractToExce l()
    {
    Microsoft.Offic e.Interop.Excel .ApplicationCla ss excel = new Microsoft.Offic e.Interop.Excel .ApplicationCla ss();
    excel.Applicati on.Workbooks.Ad d(true) ;
    DataTable inventoryTable = this.inventoryD ataSet.Tables["Inventory"];
    try
    {
    int cIndex = 0;
    foreach (DataColumn col in inventoryTable. Columns)
    {
    cIndex++;
    excel.Cells[1, cIndex] = col.ColumnName;
    }//end foreach

    int rIndex = 0;
    foreach (DataRow row in inventoryTable. Rows)
    {
    rIndex++;
    cIndex = 0;
    foreach (DataColumn col in inventoryTable. Columns)
    {
    cIndex++;
    excel.Cells[rIndex + 1, cIndex] = row[col.ColumnName].ToString();
    }//end foreach
    }//end foreach
    excel.Save("Inv entory.xls");
    excel.Workbooks .Close();
    }//end try
    catch
    { }
    }//fnExtractToExce l

    But each time when I try to extract via a menuItem, it creates Inventory.xls for me and prompts if I want to save the changes made to Sheet1.xls. I do not understand from where did sheet1.xls has creeped into my program.
    My aim is to allow the user to save the file at different locations (or at same location with a different name) each time when he wants to, without having to prompt him about previous file.Do I need to make use of a save dialogbox?

    Thank You All In advance

    ArtTeam.
Working...