Solved

Excel create object is slow

Posted on 2016-08-11
43
40 Views
Last Modified: 2016-08-12
Hello,

How can i speed up the Set oExcel = CreateObject("Excel.Application") process from vb.net 2015 desktop app.
Cheers
0
Comment
Question by:RIAS
  • 25
  • 14
  • 4
43 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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
 
LVL 19

Expert Comment

by:darbid73
Comment Utility
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
 

Author Comment

by:RIAS
Comment Utility
Thanks Experts , will post the entire code in couple of hours.
0
 

Author Comment

by:RIAS
Comment Utility
 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
 

Author Comment

by:RIAS
Comment Utility
Is it possible to give an example of


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

Thanks
0
 
LVL 19

Assisted Solution

by:darbid73
darbid73 earned 250 total points
Comment Utility
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
 

Author Comment

by:RIAS
Comment Utility
darbid73,

Any suggestion on threading to create object on the app load.
And then I can use getobject
0
 
LVL 19

Expert Comment

by:darbid73
Comment Utility
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
 

Author Comment

by:RIAS
Comment Utility
Cheers darbid73!

Hello Éric Moreau,

Any suggestions on threading!
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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
 

Author Comment

by:RIAS
Comment Utility
It takes around 4-5 minutes
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
4 to 5 minutes to execute "Set oExcel = CreateObject("Excel.Application")" ?
0
 

Author Comment

by:RIAS
Comment Utility
Yes
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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
 

Author Comment

by:RIAS
Comment Utility
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
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
and, again, how long does it take to just open a standalone Excel (forget your application), just Excel?
0
 

Author Comment

by:RIAS
Comment Utility
4-5 min  for Set oExcel = CreateObject("Excel.Application")"
0
 

Author Comment

by:RIAS
Comment Utility
and then the rest of the code gets executed.
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
and, again, how long does it take to just open a standalone Excel (forget your application), just Excel?
0
 

Author Comment

by:RIAS
Comment Utility
Eric,
Excel from office opens very opens quickly.
0
 

Author Comment

by:RIAS
Comment Utility
but from app it takes 4-5 min  for Set oExcel = CreateObject("Excel.Application")"
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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
 

Author Comment

by:RIAS
Comment Utility
Its the same.
      xlapp = New Excel.Application '*** Create excel app only once.
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
again, what if you run this application from your computer (instead of from a Citrix session)?
0
 

Author Comment

by:RIAS
Comment Utility
Its the same if I run the app from my PC rather than Citrix
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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
 

Author Comment

by:RIAS
Comment Utility
Yes
0
 

Author Comment

by:RIAS
Comment Utility
Eric,

little faster than the earlier one.But still slow
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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
 

Author Comment

by:RIAS
Comment Utility
Eric, its much faster
0
 
LVL 19

Expert Comment

by:darbid73
Comment Utility
Are sure that when you start excel manually with a mouse click that excel starts at a normal speed?
0
 

Author Comment

by:RIAS
Comment Utility
Yes ,it does start at normal speed
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
>>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
 

Author Comment

by:RIAS
Comment Utility
Its basically not on citrix and have disabled antivirus.
0
 

Author Comment

by:RIAS
Comment Utility
Eric,
Should I try threading ?
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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
 

Author Comment

by:RIAS
Comment Utility
Its Mcafee
0
 

Author Comment

by:RIAS
Comment Utility
Will try threading.
Any suggestion on how to go for asynchronous threading just to create excel
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
>>Will try threading.

it won't solve your issue.
0
 

Author Comment

by:RIAS
Comment Utility
Cannot disable mcafee on citrix.
0
 

Author Comment

by:RIAS
Comment Utility
need to have a workaround
0
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 250 total points
Comment Utility
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
 

Author Closing Comment

by:RIAS
Comment Utility
Cheers! Cant thank you enough for being so patient and guiding in the right direction
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now