[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 225
  • Last Modified:

Excel create object is slow

Hello,

How can i speed up the Set oExcel = CreateObject("Excel.Application") process from vb.net 2015 desktop app.
Cheers
0
RIAS
Asked:
RIAS
  • 25
  • 14
  • 4
2 Solutions
 
Éric MoreauSenior .Net ConsultantCommented:
how long does it take?

one way of speeding up could be to create the instance when the application starts (maybe in a thread if you) so that it is ready to use when you need it.
0
 
darbid73Commented:
There are many reasons why it's running slow. First could simply be your computer. Have you tried disabling all adding etc in excel to see if that improves it? See what Microsoft here uses https://support.microsoft.com/en-us/kb/302094. They use New.

Do you first try to getObject in case the user already has it open?


I'm not sure that you should ever introduce threading into any Microsoft Office programming.
0
 
RIASAuthor Commented:
Thanks Experts , will post the entire code in couple of hours.
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
RIASAuthor Commented:
 Public Sub ExportToExcel()
        Dim ClsFrmMain As New ClsFrmMainLoad
        Dim sVer As String = ""
        Dim sVer2 As String = ""
        Dim iHandle As IntPtr
        Dim flgRemoveitem As Boolean = True
        With ClsFrmMain
            Me.TabCntrlSearchSp.SelectedIndex.ToString()
            Dim intTabnumber As Integer
            Dim IntNewExcelObj As Integer
            Dim xlapp As Excel.Application
            Dim StrTabname As String = String.Empty 'Selected table name to be used as sheetname in excel file
            Dim FlgExportExcel As Boolean = False 'Flag to set record exported to excel 
            Dim FlgExportExcelSuccess As String = "False" 'Success for excel export
            For intTabnumber = 0 To 9
                If IsNothing(dg(intTabnumber)) = False Then
                    Dim dtSelectedRows As DataTable = .CreateDataTableFromSelectedRows(dg(intTabnumber))
                    If IsNothing(dtSelectedRows) = False Then
                        If TypeOf CType(dg(intTabnumber), DataGridView).DataSource Is DataView = False Then
                            If FlgExportExcel = False Then
                                Me.Cursor = Cursors.WaitCursor
                             [b]   xlapp = New Excel.Application '*** Create excel app only once.[/b]
                                Application.DoEvents()
                                IntNewExcelObj = 0
                            End If
                            FlgExportExcel = True
                            '*******Open file dialog for the path  *******************
                            If IntNewExcelObj = 0 Then
                                StrExcelLocation = .ReturnDevAreaPath()
                            End If
                            '*******End of Open file dialog for the path **************
                            Select Case intTabnumber
                                Case 0
                                    StrTabname = "Dy"
                                Case 1
                                    StrTabname = "Corr"
                                Case 2
                                    StrTabname = "Directory"
                                Case 3
                                    StrTabname = "Inter"
                                Case 4
                                    StrTabname = "St"
                                Case 5
                                    StrTabname = "REFERENCE"
                                Case 6
                                    StrTabname = "REQUEST"
                                Case 7
                                    StrTabname = "CAR"
                                Case 8
                                    StrTabname = "NEW_SUPPLIER_FORM"
                                Case 9
                                    StrTabname = "CLINIC"
                            End Select
                     [b]       FlgExportExcelSuccess = .ExportToExcel(IntNewExcelObj, dtSelectedRows, StrExcelLocation, StrTabname, xlapp)[/b]
                            Me.Cursor = Cursors.WaitCursor
                            IntNewExcelObj = 1
                        End If
                    End If
                End If

                If intTabnumber = 9 And FlgExportExcelSuccess = "True" Then
                    Dim result As Integer = MessageBox.Show("Do you want to open this Excel file?", "Excel file open", MessageBoxButtons.YesNo)
                    If result = DialogResult.Yes Then
                        .OpenExcel(StrExcelLocation) 'Open excel created
                        Application.DoEvents()
                        Me.Cursor = Cursors.WaitCursor
                    End If
                    If result = DialogResult.No Then
                        .FormatMessage(4, "", StrExcelLocation)
                    End If
                End If
            Next
            If FlgExportExcel = False Then
                .FormatMessage(5, "")
            ElseIf FlgExportExcelSuccess = "False" Then
                .FormatMessage(6, "")
            ElseIf FlgExportExcelSuccess = "Cancelled" Then
            End If
            Me.Cursor = Cursors.Default
            If IsNothing(xlapp) = True Then Exit Sub
            sVer = xlapp.Version
            iHandle = IntPtr.Zero
            If Val(sVer) >= 10 Then
                iHandle = New IntPtr(CType(xlapp.Parent.Hwnd, Integer))
                sVer = xlapp.Version
                iHandle = IntPtr.Zero
                .EnsureProcessKilled(iHandle, xlapp.Caption)
                System.Threading.Thread.Sleep(500)
            End If
        End With
    End Sub

Open in new window

 Function ExportToExcel(ByVal intCreateNew As Integer, ByVal dtGridData As DataTable, ByVal FilePath As String, ByVal StrSheetname As String, Optional ByVal xlApp As Excel.Application = Nothing) As String
        Dim xlWorkBook As Excel.Workbook = Nothing
        Dim xlWorkSheet As Excel.Worksheet = Nothing
        Application.DoEvents()
        Try
            FrmMain.Cursor = Cursors.WaitCursor
            xlApp.DisplayAlerts = False
            If intCreateNew = 0 Then
                xlApp.Workbooks.Add()
            End If
            If IsNothing(FilePath) = True Then
                xlWorkSheet = Nothing
                xlWorkBook = Nothing
                xlApp = Nothing
                FrmMain.Cursor = Cursors.Default
                Return "Cancelled"
                Exit Function
            End If
            xlApp.Workbooks(1).SaveAs(FilePath)
            Application.DoEvents()
            'If System.IO.File.Exists(FilePath) Then
            'Else
            '    xlApp.Workbooks(1).Save()
            '    xlWorkBook = xlApp.Workbooks
            'End If
            xlWorkBook = xlApp.Workbooks.Open(FilePath)
            Application.DoEvents()
            If intCreateNew = 0 Then
                xlWorkSheet = xlWorkBook.Worksheets(xlWorkBook.Worksheets.Count)
            Else
                xlWorkBook.Worksheets.Add(After:=xlWorkBook.Worksheets(xlWorkBook.Worksheets.Count))
                xlWorkSheet = xlWorkBook.Worksheets(xlWorkBook.Worksheets.Count)
            End If
            xlWorkSheet.Name = StrSheetname
            With xlWorkSheet.PageSetup
                .PrintGridlines = True
                .CenterHeader = StrSheetname
                .Zoom = False
            End With
            Dim dtRowCount As Integer = dtGridData.Rows.Count
            Dim dtColCount As Integer = dtGridData.Columns.Count
            Dim objXlColHeaderData(1, dtGridData.Columns.Count) As Object
            Application.DoEvents()
            For i As Integer = 0 To dtColCount - 1
                objXlColHeaderData(0, i) = dtGridData.Columns(i).ColumnName
            Next
            Dim objXlData(dtRowCount, dtColCount) As Object
            For iRow As Integer = 0 To dtRowCount - 1
                Application.DoEvents()
                For iCol As Integer = 0 To dtColCount - 1
                    Application.DoEvents()
                    If Not IsDBNull(dtGridData.Rows(iRow).Item(iCol)) Then
                        objXlData(iRow, iCol) = dtGridData.Rows(iRow).Item(iCol)
                    Else
                        objXlData(iRow, iCol) = ""
                    End If
                Next
            Next
            Dim xlRange As Excel.Range = xlWorkSheet.Range("A1")
            xlRange = xlRange.Resize(dtRowCount + 1, dtColCount)
            xlRange.Value = objXlColHeaderData
            xlWorkSheet.Range(xlWorkSheet.Cells(1, 1), xlWorkSheet.Cells(1, dtColCount)).Font.Bold = True
            xlRange = xlWorkSheet.Range("A2")
            xlRange = xlRange.Resize(dtRowCount, dtColCount)
            xlRange.Value = objXlData
            With xlWorkSheet
                .Range(.Cells(1, 1), .Cells(1, 1)).Select()
            End With
            With xlWorkSheet.Application.ActiveWindow
                .SplitColumn = 0
                .SplitRow = 1
            End With
            xlWorkSheet.Cells.EntireColumn.AutoFit()
            xlWorkSheet.Application.ActiveWindow.FreezePanes = True
            Application.DoEvents()
            xlWorkBook.Save()

        Catch ex As Exception
            MessageBox.Show(ex.Message, "ErrorIn ExportToExcel", MessageBoxButtons.OK, MessageBoxIcon.Error)
            xlWorkSheet = Nothing
            xlWorkBook = Nothing
            xlApp = Nothing
            FrmMain.Cursor = Cursors.Default
        Finally
            FrmMain.Cursor = Cursors.Default
        End Try
        Return "True"
    End Function

Open in new window

0
 
RIASAuthor Commented:
Is it possible to give an example of


Do you first try to getObject in case the user already has it open?

Thanks
0
 
darbid73Commented:
No problem.

See MSDN. It actually uses as an example Excel.

' Test to see if a copy of Excel is already running. 
Private Sub testExcelRunning()
    On Error Resume Next 
    ' GetObject called without the first argument returns a 
    ' reference to an instance of the application. If the 
    ' application is not already running, an error occurs. 
    Dim excelObj As Object = GetObject(, "Excel.Application")
    If Err.Number = 0 Then
        MsgBox("Excel is running")
    Else
        MsgBox("Excel is not running")
    End If
    Err.Clear()
    excelObj = Nothing 
End Sub

Open in new window

Code from Microsoft in case the link is dead.

I always use code like this first for Office as it can be that the user already has an instance open.  Especially when it comes to Outlook which is usually always on.


Here is an alternative. Which is similar.
0
 
RIASAuthor Commented:
darbid73,

Any suggestion on threading to create object on the app load.
And then I can use getobject
0
 
darbid73Commented:
I am not an expert on threading and office.  It is my opinion that you simply should not mix threading and the office object model.  You can use a thread to for example go and perform a HTTP request or query a SQL database but you need to come back to the UI thread when you use the Office Object model.

If you do a Google Search on this topic you will find a massive amount of information and opinions on it.  So I am neither alone with my opinion nor right as I am sure people will give example where you can use threads.

Maybe Eric could elaborate on how he thought you might do it.
0
 
RIASAuthor Commented:
Cheers darbid73!

Hello Éric Moreau,

Any suggestions on threading!
0
 
Éric MoreauSenior .Net ConsultantCommented:
before going to the threading option:
-how long does it take? (I already asked this)
-How long does it take to just open Excel standalone?
0
 
RIASAuthor Commented:
It takes around 4-5 minutes
0
 
Éric MoreauSenior .Net ConsultantCommented:
4 to 5 minutes to execute "Set oExcel = CreateObject("Excel.Application")" ?
0
 
RIASAuthor Commented:
Yes
0
 
Éric MoreauSenior .Net ConsultantCommented:
just that line, not the whole process takes 4-5 minutes?

how long does it take to start Excel standalone?

I have never seen it taking so long. Have you checked your computer for viruses, malware, ... ?
0
 
RIASAuthor Commented:
Hi,
my application is running on Citrix and just to open ,i.e New excel it takes 4-5 minutes.
Yes,It is free of virus ,malware etc
0
 
Éric MoreauSenior .Net ConsultantCommented:
and, again, how long does it take to just open a standalone Excel (forget your application), just Excel?
0
 
RIASAuthor Commented:
4-5 min  for Set oExcel = CreateObject("Excel.Application")"
0
 
RIASAuthor Commented:
and then the rest of the code gets executed.
0
 
Éric MoreauSenior .Net ConsultantCommented:
and, again, how long does it take to just open a standalone Excel (forget your application), just Excel?
0
 
RIASAuthor Commented:
Eric,
Excel from office opens very opens quickly.
0
 
RIASAuthor Commented:
but from app it takes 4-5 min  for Set oExcel = CreateObject("Excel.Application")"
0
 
Éric MoreauSenior .Net ConsultantCommented:
it is surely related to Citrix.

what if you run this application from your computer (instead of from a Citrix session)?

are you using Early binding or late binding (https://support.microsoft.com/en-us/kb/245115)? how is your oExcel declared?
0
 
RIASAuthor Commented:
Its the same.
      xlapp = New Excel.Application '*** Create excel app only once.
0
 
Éric MoreauSenior .Net ConsultantCommented:
again, what if you run this application from your computer (instead of from a Citrix session)?
0
 
RIASAuthor Commented:
Its the same if I run the app from my PC rather than Citrix
0
 
Éric MoreauSenior .Net ConsultantCommented:
I have never seen creating an instance of Excel taking 4-5 minutes.

To debug the issue, I would create a brand new dummy application containing only a form. On that form I would add a button that would only do a "dim x as new Excel.Application" (you will need a reference to Excel). I would test this on my computer and then on Citrix. Can you do that?
0
 
RIASAuthor Commented:
Yes
0
 
RIASAuthor Commented:
Eric,

little faster than the earlier one.But still slow
0
 
Éric MoreauSenior .Net ConsultantCommented:
on your own PC without having Citrix around? This is just not making any sense! Do you have another computer on which you can test? Can you turn off your antivirus for a minute (you might disconnect your computer from the network for that period)?
0
 
RIASAuthor Commented:
Eric, its much faster
0
 
darbid73Commented:
Are sure that when you start excel manually with a mouse click that excel starts at a normal speed?
0
 
RIASAuthor Commented:
Yes ,it does start at normal speed
0
 
Éric MoreauSenior .Net ConsultantCommented:
>>Eric, its much faster

what have you done to be much faster? the other computer? the disabling of the antivirus? disconnection of antivirus?

You need to give us as much information as you can because we just cannot guess what is happening on your side!
0
 
RIASAuthor Commented:
Its basically not on citrix and have disabled antivirus.
0
 
RIASAuthor Commented:
Eric,
Should I try threading ?
0
 
Éric MoreauSenior .Net ConsultantCommented:
threading will never make a process faster. it will just help if you can span 2 or more processes at the same time

so if you found that the antivirus is your issue, dig into that direction. Which one is it? any updates available for it? Anything on their support site? ...
0
 
RIASAuthor Commented:
Its Mcafee
0
 
RIASAuthor Commented:
Will try threading.
Any suggestion on how to go for asynchronous threading just to create excel
0
 
Éric MoreauSenior .Net ConsultantCommented:
>>Will try threading.

it won't solve your issue.
0
 
RIASAuthor Commented:
Cannot disable mcafee on citrix.
0
 
RIASAuthor Commented:
need to have a workaround
0
 
Éric MoreauSenior .Net ConsultantCommented:
Your best bet is to contact McAfee. They are surely aware of something that can fix your issue.

As I already said, threading is not your solution. It will just take 4-5 minutes to the thread to complete but you won't have access to your Excel object faster. So it is totally useless to go that way.

A real workaround would be to use a library to replace Excel like http://www.aspose.com/products/cells/net
0
 
RIASAuthor Commented:
Cheers! Cant thank you enough for being so patient and guiding in the right direction
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 25
  • 14
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now