Загрузка net framework excel

При открытии определенного файла Excel требуется 4 минуты, чтобы сообщение Loading .NET Framework... исчезло. Как только он открывается, он работает быстро, как и ожидалось. Единственное, что я нашел, — запустить Excel в безопасном режиме. Он ведет себя так же. Я удалил все рабочие листы, подключения к внешним базам данных, Power Query, VBA, имена и сохранил их как XLSX. По-прежнему такое же поведение.
Если я закрою электронную таблицу (но не Excel) и открою ее снова, она откроется быстро.

Что еще более загадочно, так это то, что на машинах некоторых коллег он ведет себя так же, как на моем, а на других сообщение Loading .NET Framework... вообще не появляется (или его слишком быстро не заметить).

Вы знаете, как избавиться от этого сообщения, не переустановив Excel?
Спасибо.

1 ответ

Лучший ответ

Отсюда я получил ответ на свой вопрос: https: // techcommunity. microsoft.com/t5/excel/loading-net-framework-soooooo/mp/2264145/highlight/true#M95862

Вы можете избавиться от загрузки .net framework в Excel 2019, выполнив File, Info, Check for Issues / Inspect Document и отметив Custom XML Data (вы также можете отметить все остальное, но это займет много времени). Он сообщит вам, что были найдены пользовательские XML-данные, поэтому нажмите «Удалить». Затем закройте и сохраните.
В следующий раз, когда вы откроете платформу .net, это будет намного быстрее.


1

Florin
12 Апр 2021 в 15:14

Hi there,

My 2016 64 bit Excel application on Windows 10 keeps crashing when I open files that I saved with PowerPivot or PowerQuery tables or queries.  Once this behavior starts, I can no longer create new Power Queries or Power Pivot tables without Excel crashing. 
It gets to the «.net framework loading» status before Excel completely crashes.  The last time this happened, I worked with my IT team at my company to resolve the issue.  The resolution that time was that my user profile was corrupt and
needed to be reset.  The reset worked for a few a weeks but now I’m running into the crashing issue again. I believe it’s my profile again because a new Microsoft account I created today on my machine does not run into these crashing issues.  Rather
than reset my profile again I would be interested in trying to get to the root cause of the issue.

Steps taken to identify and fix issue the first time:

0) Ran excel in safe mode and also toggled on and off the PowerQuery, PowerMap and PowerPivot plugins.  Still crashes.

1) Checked event viewer for logs.  At time of crash, there is an application error that reads as follows:

«.NET Runtime version 2.0.50727.8745 — Fatal Execution Engine Error (00007FF8D66B0D3E) (80131506)»

2) Tried to re-install .net framework on machine but Excel still crashes when it tries to launch a power query prompt.

3) Tried to re-install office from C2R but Excel still crashes when it tries to launch a power query prompt.

4) Ran OffCat to identify issues but it did not identify anything of note.

5) Profile and AppData folder was reset which finally allowed PowerQuery to run.

Potential items I performed that may have re-corrupted profile:

1) installed AutoHotKey

2) installed SciTE4AutoHotKey

3) Installed «the Admin Script Editor» for powershell development

4) Installed Pulover’s Macro Creator

5) Developed some powershell queries to open up a Word com object and modify word documents located in a directory

After these steps, Excel files I created with Pivot Tables connected to SSAS will attempt to «load the .net framework» and crash. Additionally, Excel files I created with tables not connected to anything will attempt to «load the .net framework»
and crash.

Below is the OFFCAT output

Windows Info

Name = Microsoft Windows 10 Enterprise

Bitness = 64-bit

Version = 10.0.14393

Service Pack Level = RTM

Windows Directory = C:WINDOWS

Hardware Info

Machine Name =

Computer Manufacturer = Hewlett-Packard

Virtual Machine = False

Touch Enabled = False

Software Info

Default Browser = «C:Program FilesInternet ExplorerIEXPLORE.EXE» %1

Antivirus «Windows Defender» is not enabled and up to date

Antivirus «McAfee VirusScan Enterprise» is enabled and up to date

Office Info

SKU = Microsoft Office 365 ProPlus

Bitness = x64

Service Pack Level =

Installation Type = ClickToRun

Installation Folder = C:Program FilesMicrosoft OfficerootOffice16

Build Info

EXCEL.exe

Path = C:Program FilesMicrosoft OfficerootOffice16EXCEL.EXE

Build = 16.0.7766.2096

Mso.dll

Path = C:Program FilesMicrosoft OfficerootvfsProgramFilesCommonx64Microsoft SharedOFFICE16mso.dll

Build = 16.0.7726.1049

Oart.dll

Path = C:Program FilesMicrosoft OfficerootOffice16oart.dll

Build = 16.0.7726.1049

Vbe7.dll

Path = C:Program FilesMicrosoft OfficerootvfsProgramFilesCommonx64Microsoft SharedVBAVBA7.1VBE7.dll

Build = 7.1.10.56

Fm20.dll

Path = C:Program FilesMicrosoft OfficerootvfsSystemFM20.dll

Build = 16.0.7726.1049

ClickToRun

Build = 16.0.7766.2096

Latest Version =

Updating Enabled = False

C2R Channel = undocumented channel

Registered add-ins

HKEY_CURRENT_USER

HKEY_LOCAL_MACHINE

Microsoft Power Map for Excel

Inquire

  • Edited by

    Wednesday, September 20, 2017 2:34 PM
    adding more specifics to title

Introduction

It’s fairly straightforward to call a .NET Framework library directly from Excel on Windows, particularly if you are using Visual Studio.  You don’t need Visual Studio Tools for Office.  However there doesn’t seem to be an easy guide on the internet anywhere. The Microsoft documentation is quite good on the subject, but can be a little confusing. This article is an attempt to redress the situation.

This article was updated in May 2020 to cover the latest versions of Visual Studio and Excel.  The article was originally written in 2007 and will work with all versions of Visual Studio and Excel since that date.

.NET Core

The approach below will NOT work with any version of .NET Core or .NET 5.  The last version of .NET this walk through will work with is the .NET Framework 4.8.

A Basic Walk Through

We’ll start by walking through a very basic example. We’ll get Excel to call a .NET method that takes a string as input (for example “ World”) and returns “Hello” concatenated with that input string (so, for example, “Hello World”).

1. Create a C# Windows Class Library (.NET Framework) project in Visual Studio called ‘DotNetLibrary’. It doesn’t matter which folder this is in for the purposes of this example.

2. To call a method in a class in our library from Excel we need the class to have a default public constructor. Obviously the class also needs to contain any methods we want to call. For this walk through just copy and paste the following code into our default class file:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace DotNetLibrary
{
    public class DotNetClass
    {
        public string DotNetMethod(string input)
        {
            return "Hello " + input;
        }
    }
}

That’s it: if you look at existing articles on the web, or read the MSDN help, you might think you need to use interfaces, or to decorate your class with attributes and GUIDs. However, for a basic interop scenario you don’t need to do this.

3. Excel is going to communicate with our library using COM. For Excel to use a COM library there need to be appropriate entries in the registry. Visual Studio can generate those entries for us.

To do this bring up the project properties (double-click ‘Properties’ in Solution Explorer). Then:

i) On the ‘Application’ tab click the ‘Assembly Information…’ button. In the resulting dialog check the ‘Make assembly COM-visible’ checkbox. Click ‘OK’.

ii) On the ‘Build’ tab check the ‘Register for COM interop’ checkbox (towards the bottom: you may need to scroll down).

If you are working with 64-bit Excel then you may need to set the Platform Target in the Build properties to x64: thanks to danh for a comment to this effect.

4. Build the library.  You need Visual Studio to be running as an administrator for this to work because it’s putting COM entries in the registry.  If it’s not just right-click your Visual Studio icon and ‘Run As Administrator’.

5. Now start Excel and open a new blank workbook. Open the VBA code editor.  This can be tricky to find: you have to get the Developer tab visible on the Ribbon if it’s not already set up. To do this click the File tab, then click Options, Customize Ribbon, and under ‘Customize the Ribbon’ make sure ‘Main Tabs’ is selected in the dropdown, and then check the Developer checkbox. Now click the Developer tab, then click Visual Basic.

6. We now need to include a reference to our new library. Select ‘References’ on the Visual Basic Editor’s ‘Tools’ menu. If you scroll down in the resulting dialog you should find that ‘DotNetLibrary’ is in the list. Check the checkbox alongside it and click ‘OK’.

7. Now open the code window for Sheet1 (double click Sheet1 in the Project window). Paste the VBA code below into the code window for Sheet1:

Private Sub TestDotNetCall()

Dim testClass As New DotNetClass

MsgBox testClass.DotNetMethod(“World”)

End Sub

8. Click anywhere in the code you’ve just pasted in and hit ‘F5’ to run the code. You should get a ‘Hello World’ message box.

Getting Intellisense Working in Excel

Whilst the VBA code above compiles and executes, you will discover that intellisense is not working in the code editor. This is because by default our library is built with a late binding (run-time binding) interface only. The code editor therefore doesn’t know about the types in the library at design time.

There are good reasons for only using a late-bound interface by default: with COM versioning libraries can become difficult with early-bound interfaces. In particular, if you change the early-bound interface by adding, for example, a method in between two existing methods you are likely to break existing clients as they are binding based on the order of the methods in the interface.

For similar reasons you are heavily encouraged to code your interface separately as a C# interface and then implement it on your class, rather than using the default public interface of the class as here. You then should not change that interface: you would implement a new one if it needed to change.

For more on this see:

https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.classinterfaceattribute(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.classinterfacetype(v=vs.110).aspx

However, we can build our library to use early bound interfaces, which means intellisense will be available. To do this we need to add an attribute from the System.Runtime.InteropServices namespace as below:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
 
namespace DotNetLibrary
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class DotNetClass
    {
        public DotNetClass()
        {
        }
        public string DotNetMethod(string input)
        {
            return "Hello " + input;
        }
    }
}

If you change your code as above it will expose an ‘AutoDual’ interface to COM. This means it is still exposing the late-bound interface as before, but now also exposes an early-bound interface. This means intellisense will work.

To get this working:

1. Save your workbook and close Excel.  Excel will lock the DotNetLibrary dll and prevent Visual Studio from rebuilding it unless you close it.  Remember you need to save your new code module.  Unless you are using a version of Excel prior to Excel 2007 you need to change the type: save it as type Excel Macro-Enabled Workbook (*.xlsm).

2. Go back into Visual Studio, change the DotNetClass as shown above, and rebuild the library.  Note there’s a new ‘using’ statement as well as the attribute line.

3. Re-open your Excel spreadsheet.  Once again if you are using a recent version of Excel there is an extra step: you need to explicitly enable macros.  A warning bar will appear beneath the ribbon saying the ‘Macros have been disabled’.  Click the ‘Enable content’ button and that should disappear.

4. Get the VBA code window up again (see item 5 above).

5. Excel can get confused about the interface changes unless you re-reference the library. To do this go to Tools/References. The DotNetLibrary reference should be near the top of the list now. Uncheck it and close the window. Now open the window again, find the library in the list, and re-check it (trust me, you need to do this).

6. Now run the code and it should still work (put a breakpoint in the routine and hit F5).

7. Enter a new line in the routine after the ‘MsgBox’ line, and type ‘testClass.’. When you hit the ‘.’ you should get an intellisense dropdown which shows that DotNetMethod is available. See below.

Intellisense in Excel

Let me re-iterate that this works and is fine for development, but for release code you are better off using the default late binding interfaces unless you understand the full versioning implications. That is, you should remove the ClassInterface attribute from your code when you do a release.

Deployment

In the example here we are using Visual Studio to register our .NET assembly on the workstation so that Excel can find it via COM interop. However, if we try to deploy this application to client machines we’re not going to want to use Visual Studio.

Microsoft have provided a command-line tool, regasm.exe, which can be used to register .NET assemblies for COM interop on client workstations. It can also be used to generate a COM type library (.tlb) separate from the main library (.dll), which is considered good practice in general.  You can find regasm.exe in the .NET framework folder: C:WindowsMicrosoft.NETFrameworkv4.0.30319 or similar.

As usual with .NET assemblies you have the choice of strong-naming your assembly and installing it in the GAC, or of not strong-naming it and including it in a local path. If you have strong-named your assembly and installed it in the GAC all you need to do is bring up an administrator Visual Studio command prompt and run:

regasm DotNetLibrary.dll

If you have not strong-named your assembly you need to tell regasm.exe where it is so that it can find it to register it. To do this you need to run the command below, where c:ExcelDotNet is the path where DotNetLibrary.dll can be found. This works fine, although it will warn you that you should really strong-name your assembly:

regasm /codebase c:ExcelDotNetDotNetLibrary.dll

Note that you can unregister an assembly with the /u option of regasm.

For more detail on this see https://docs.microsoft.com/en-us/dotnet/framework/tools/regasm-exe-assembly-registration-tool

Debugging into .NET from Excel

You may want to debug from Excel into your class library. To do this:

1. Using Visual Studio bring up the Properties window for the class library.

2. Go to the Debug tab and select the ‘Start external program’ option under ‘Start Action’. In the textbox alongside enter the full path including file name to Excel.exe for the version of Excel you are using (usually in Program Files (x86)Microsoft OfficerootOffice16 or Program FilesMicrosoft OfficeOffice).

3. On the same Debug tab under ‘Command line arguments’ enter the full path including file name to your test workbook (the .xlsm file). Once you’re done it should something like below::

Project Properties for Excel

4. Now put a breakpoint in the code (in our example the sensible place is in method DotNetMethod) and hit F5 in the .NET project. The .NET code should compile and Excel should start with your workbook opened. If you now run the VBA code to call the .NET library again, as above, you should find that the code will break at the breakpoint you set in the .NET code.

Possible Problem with these Examples

One problem we have had with these examples is that Excel can get confused about which version of the .NET Framework to load if you have more than one version installed. If this happens you will get an automation error when you try to instantiate .NET objects at runtime from Excel. The .NET types will appear correctly in the Excel object browser.

The workaround for this is to tell Excel explicitly that the version of the .NET Framework that you are using is supported. To do this create a text file called Excel.exe.config and put it in the same directory as Excel.exe itself. The file should contain the text below (with the version number replaced with the .NET Framework version you are using):

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

References:

Index page from MSDN

https://docs.microsoft.com/en-us/dotnet/framework/interop/exposing-dotnet-components-to-com

More on COM Interop from COM clients into .NET:

https://www.codeproject.com/Articles/7587/Exposing-COM-interfaces-of-a-NET-class-library-for

Guidelines for COM Interoperability from .NET

https://blogs.msdn.microsoft.com/heaths/2005/03/09/guidelines-for-com-interoperability-from-net-2/

Excel/.NET versioning problems

http://krgreenlee.blogspot.com/2006/01/software-running-excel-with-net-11.html

Добрый день.

Прошу помочь, так так мои специалисты по ПК (аля  поддержка в фирме) не могут понять причину и вообще зачем он мне  какой-то PQ в работе .
До  определенного момента я работала с запросами в PQ и Excel летал, ну  практически летал. Потом в 18:00 на мой взгляд автоматически сработала  какое-то обновление не знаю уж где, может на сервере, может еще где (я  лишь предполагаю, сама чайник в этом) и PQ наотрез перестал  работать-зависает и Excel только убивать в данном случае. Мне моя  поддержка предлагает просто снести Excel и переустановить до версии  2021, но я думаю, что возможно игра не стоит свеч и ошибка не уйдет. Пробовала на других файлах запустить PQ, если файл совсем маленький, PQ сработал, а на больших таблицах хоть уже существующие подключения PQ не открывает, и новые в других больших файлах не создает. Все файлы с которыми я  работаю лежат на сетевом диске ,но пробовала и на диск C перетащить, все равно не работает PQ. Framework тех. поддержка обновила. В Параметры/Надстройки/Отключенные объекты заходила, написано — Отключенные объекты отсутствуют.

Скриншот Диспетчера задач прикладываю

Изменено: Марина Березан26.12.2022 17:58:03

How can I specify that Excel uses the .NET framework version 2.0 when running .NET dlls other than adding an excel.exe.config file to the Office Binary folder?

Our application runs in Excel and uses VBA which makes calls into managed code in .NET assemblies. I believe the textbook way of doing this is to add excel.exe.config to the Office binary directory containing:

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

This option is not acceptable for our clients, firstly because they simply won’t allow us to add files to the Office directory and even if they did we could not risk breaking some application using .NET v1.1 which is the default choice of Excel.

The solution which we thought would work was to copy the Excel.exe file to our own applications directory from the client’s Office directory, to add the config file there and execute that file. It works well but we are having serious installation problems where the install script cannot find the correct version of Excel. Plus it’s a nasty kludge in the first place.

Any ideas would be welcome. I wonder if a layer of unmanaged (non .NET) code in a DLL might work. Some advice on how to do this or some simpler alternative would be appreciated as this is non-trivial.

Related:

.NET app.config question

Понравилась статья? Поделить с друзьями:
  • Загрузка excel файлов в power bi
  • Загрузка excel таблицы в табличный документ
  • Загрузка excel для 1с розница
  • Загрузка excel в массив
  • Загрузка excel в mysql php