How do you not create a new excel file but insert in an excel file? RRS feed

  • Question

  • Im using this code to create and excel file. But im having an excel file with a kinda of layout. So i dont want to create a new file i want to insert it in the excel file with layout.

    private void button2_Click(object sender, EventArgs e)
          Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
          Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
          object misValue = System.Reflection.Missing.Value;
          Excel.Range chartRange;
          Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
          xlWorkBook = xlApp.Workbooks.Add(misValue);
          xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
          xlWorkSheet.Shapes.AddPicture("logo.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 5, 10, 125, 87); 
          //xlWorkSheet.Cells[4, 2] = "";
          xlWorkSheet.Cells[3, 4] = "Some text";
          chartRange = xlWorkSheet.get_Range("d3");
          chartRange.Font.Bold = true;
          xlWorkSheet.Cells[4, 4] = "More text";
          xlWorkSheet.Cells[5, 4] = "more and more text";
          xlWorkSheet.Cells[3, 10] = "Text with box";
          chartRange = xlWorkSheet.get_Range("j3", "k5");
          chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);      
          xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
          xlWorkBook.Close(true, misValue, misValue);
          MessageBox.Show("File created !");
    So the question is how do i insert in an excel file?

    Tuesday, January 18, 2011 5:03 PM


  • Try code that does something along the lines of this, showing the logic but not the actual code, since I only know VBA.

    Your logic will need to change as well....

    On Error GoTo MakeNew
    xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls");
    'Code to add values
    Exit Sub
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    'Code to create the structure, and add values


    HTH, Bernie
    • Proposed as answer by Bruce Song Wednesday, January 19, 2011 6:43 AM
    • Marked as answer by TALES75 Wednesday, January 19, 2011 11:38 AM
    Tuesday, January 18, 2011 7:52 PM