View Single Post
 
Old 06-17-2012, 04:00 AM
Colin Legg's Avatar
Colin Legg Colin Legg is offline Windows 7 32bit Office 2010 32bit
Expert
 
Join Date: Jan 2011
Location: UK
Posts: 369
Colin Legg will become famous soon enough
Default

I started a new forms project, added a button to the form and added a reference to Excel 2007 COM library and then put this simplified version of your code in my project. It ran without issue and no hanging when test report was opened. Do you have any problems when running this code?
Code:
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public static int Counter = 0;
        public String strPath = "";
        public void CreateExcel()
        {
            Counter = Counter + 1;
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            xlWorkSheet.Cells.get_Item(1, 1).Value2 = "TEST";
            string strTempPath = System.Environment.GetEnvironmentVariable("TEMP");
            DirectoryInfo objInfo = new DirectoryInfo(strTempPath);
            strPath = strTempPath + "\\Excel" + Counter + ".xls";
            xlWorkBook.SaveAs(strPath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Marshal.FinalReleaseComObject(xlWorkSheet);
            xlWorkBook.Close(true, misValue, misValue);
            Marshal.FinalReleaseComObject(xlWorkBook);
            xlApp.Quit();
            Marshal.FinalReleaseComObject(xlApp);
            
        }
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            CreateExcel();
        }
    }
}
__________________
Colin

RAD Excel Blog
Reply With Quote