Datagridview to excel

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

    Datagridview to excel

    Hi All,

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

    Code:
    private void fnExtractToExcel()
    {
    Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
    excel.Application.Workbooks.Add(true) ;
    DataTable inventoryTable = this.inventoryDataSet.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("Inventory.xls");
    excel.Workbooks.Close();
    }//end try
    catch
    { }
    }//fnExtractToExcel
    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.
    Last edited by kenobewan; Mar 7 '07, 11:42 PM. Reason: Add code tags
  • kenobewan
    Recognized Expert Specialist
    • Dec 2006
    • 4871

    #2
    What happens if you cancel the prompt? If you get an exception, then you have found a bug that allows the sheet to be saved in two places - hence the save as sheet1.xls. Suggest using another method.

    Comment

    • artteam
      New Member
      • Feb 2007
      • 18

      #3
      Originally posted by kenobewan
      What happens if you cancel the prompt? If you get an exception, then you have found a bug that allows the sheet to be saved in two places - hence the save as sheet1.xls. Suggest using another method.
      I appreciate for taking time. Could you be more specific. I did not understand when you say cancelling the prompt. I myself not aware of from where the prompt is generated.

      Thank you in advance....

      Sudhamsh Mahankali

      Comment

      Working...