Как подключить word к visual studio
Перейти к содержимому

Как подключить word к visual studio

  • автор:

Opening Word Document through code in Visual Studio C#

The problem is HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID <000209FF-0000-0000-C000-000000000046>cannot be registered. Although the class exists (Microsoft.Office.Interop.Word.ApplicationClass) in your registry, does not mean it has been registered. Microsoft doesn’t allow the Microsoft.Office.Interop.Word.dll to be registered for some unexplainable reason and as a result, if you are referencing «ApplicationClass» class in your code; you’ll run into this issue when deployed to an actual server. You won’t get an error message/warning on your local/build machine. HERE’s what the generic error may look like:

Retrieving the COM class factory for component with CLSID <000209FF-0000-0000-C000-000000000046>failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Как подключить word к visual studio

На выходе получается солюшен с двумя проектами:

public partial class ThisAddIn
private void ThisAddIn_Startup( object sender, System. EventArgs e)
new AddInApplication().Run();
>

private void ThisAddIn_Shutdown( object sender, System. EventArgs e)
>

#region VSTO generated code

/// <summary>
/// Required method for Designer support — do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
this .Startup += new System.EventHandler(ThisAddIn_Startup);
this .Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
>

* This source code was highlighted with Source Code Highlighter .

internal sealed class AddInApplication : WindowsFormsApplication<AddInWorkItem, object >
protected override void Start()
>
>

* This source code was highlighted with Source Code Highlighter .

Модель приложения Word Add-in
Modal Workspace

Workspaces.Add(( new SimpleModalWorkspace() ), WorkspaceNames.MainWorkspace);

* This source code was highlighted with Source Code Highlighter .

Фабрика элементов управления Microsoft Word
  1. В массив тулбаров Microsoft Word вставляется тулбар
  2. В коллекцию кнопок на тулбаре вставляется кнопка
  3. В кнопку уже ничего не вставляется (не рассматриваем случае комбобоксов, хотя они присутствуют), поэтому это терминальный объект
  1. IWordCommandBarContainer — контейнер тулбаров Microsoft Word
  2. IWordCommandBar — контейнер кнопок на тулбаре
  3. IWordButton — кнопка

public class CommandBarUIAdapterFactory : IUIElementAdapterFactory
public IUIElementAdapter GetAdapter( object uiElement)
if ( uiElement is IWordCommandBarContainer ) //тулбары
return new CommandBarUIAdapter(( IWordCommandBarContainer )uiElement);
if ( uiElement is IWordCommandBar ) //кнопки в тулбарах
return new CommandBarButtonUIAdapter(( IWordCommandBar )uiElement);

throw new ArgumentException( «uiElement» );
>

public bool Supports( object uiElement)
return ( uiElement is IWordCommandBarContainer ) || ( uiElement is IWordCommandBar );
>
>

* This source code was highlighted with Source Code Highlighter .

internal class BarCollection : IWordCommandBarContainer
#region IWordCommandBarContainer Members

if ( commandBar == null )
commandBar = Globals.ThisAddIn.Application.CommandBars.Add(bar.Id, ( object )MsoBarPosition.msoBarTop, _null, true );

private object _null = System.Reflection.Missing.Value;

* This source code was highlighted with Source Code Highlighter .

Services.AddNew<WordUIElementFactory, IWordUIElementFactory>();
IUIElementAdapterFactoryCatalog factoryService = base .Services.Get<IUIElementAdapterFactoryCatalog>();
factoryService.RegisterFactory( new CommandBarUIAdapterFactory());

UIExtensionSites.RegisterSite(UIExtensionSiteNames.WordBarsSite, new BarCollection());

* This source code was highlighted with Source Code Highlighter .

UIExtensionSite site = _rootWorkItem.UIExtensionSites[UIExtensionSiteNames.WordBarsSite];
IWordCommandBar mainBar = site.Add<IWordCommandBar>(_factory.CreateBar( «AddInToolbar» ));

mainBar.AddButton(btn);
btn.Click += new EventHandler<WordButtonClickArgs>(ButtonClick);

* This source code was highlighted with Source Code Highlighter .

private void ButtonClick( object sender, WordButtonClickArgs e)
object smartPart = _rootWorkItem.SmartParts.AddNew<SampleSmartPart>();
WindowSmartPartInfo info = new WindowSmartPartInfo();
info.FormStartPosition = FormStartPosition.CenterScreen;
info.MaximizeBox = false ;
info.MinimizeBox = false ;
info.Resizable = false ;
info.Title = «Custom Control» ;
info.ShowInTaskbar = false ;
_rootWorkItem.Workspaces[WorkspaceNames.MainWorkspace].Show(smartPart, info);
>

* This source code was highlighted with Source Code Highlighter .

public class CustomModuleEnumerator : IModuleEnumerator
#region Constants
private const string ModuleName = «CustomModule.dll» ;
#endregion

#region IModuleEnumerator Members

public IModuleInfo[] EnumerateModules()
List <IModuleInfo> result = new List <IModuleInfo>();

string path = GetModulePath(ModuleName);
if ( File .Exists(path) )
result.Add( new ModuleInfo(ModuleName));
return result.ToArray();
>

#region Private Methods
private string GetModulePath( string assemblyFile)
if ( !Path.IsPathRooted(assemblyFile) )
assemblyFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyFile);

return assemblyFile;
>
#endregion
>

* This source code was highlighted with Source Code Highlighter .

protected override void AddServices()
base .AddServices();

RootWorkItem.Services.Remove<IModuleEnumerator>();
RootWorkItem.Services.AddOnDemand<CustomModuleEnumerator, IModuleEnumerator>();
>

* This source code was highlighted with Source Code Highlighter .

Получилось то, что задумывалось в изначальном псевдопримере:

В тулбарах Microsoft находится наш тулбар, на нем висит кнопка с иконкой, по событию нажатия кнопки вылезает пользовательский элемент управления, в текстовое поле которого с помощью кнопки можно загнать выделенный в документе текст:) Тривиально, но обратите внимание, как ничтожна связность между объектами! Хочется подметить, что у каркаса, при должном обращении, идеальная code maintainability.

Security

The operation you are performing will alter security policy.
Are you sure you want to perform this operation? (yes/no)
yes
Added union code group with «-url» membership condition to the User level.
Success

Как подключить word к visual studio

БлогNot. Visual C++: проверяем орфографию и формируем офисный документ с помощью Word

Visual C++: проверяем орфографию и формируем офисный документ с помощью Word

Приведём пример кода на Visual C++, работающего с Word. Подойдёт любая версия Visual Studio от сборки Express 2010 и выше. Похожий пример на работу с Excel приводился в этой заметке.

Создадим новый проект C++/CLI, на форме расположим поле ввода richTextBox1 и растянем его на всю форму (свойство Dock = Fill )

Добавим на форму стандартные файловые диалоги openFileDialog1 , saveFileDialog1

Добавим верхнее меню menuStrip1 с пунктами Файл — Создать, Файл — Открыть, Файл — Сохранить, Файл — Выход, запрограммируем их:

Меню Файл — Создать:
Меню Файл — Открыть:
Меню Файл — Сохранить:
Меню Файл — Выход:

    Для Visual Studio 2010 и подобных: меню Проект, Свойства, Список Общие свойства — .NET Framework и ссылки, кнопка Добавить новую ссылку. вкладка Обзор.

Добавим пункт меню Правка — Проверить и реализуем для него следующий (примерный) код:

Если офис-2007 выдаёт ошибку «Неверно указана единица измерения», попробуйте заменить файл C:\ Program Files\ (или Program Files (x86)\ ) Microsot Office\Office12\1049\ WWINTL.DLL на вот этот: скачать по ссылке

Перед заменой закройте все офисные программы и проверьте, что размеры оригинального и исправленного файлов совпадают.

Пример 2. Построение объекта в документе Word (на примере таблицы)
  • В Visual Studio 2010: вкладка COM в окне ”Добавить ссылку” – показать на библиотеку Microsoft Word 14.0 Object Library (или ваша версия вместо 14).
  • В Visual Studio 2015: список COM в окне «Добавить ссылку» – пункт Библиотеки типов — включить чекбокс «Microsoft Word 14.0 Object Library» (или ваша версия вместо 14).

Добавим к приложению пункт меню Правка — Записать отчет и реализуем следующий код:

Office Add-ins with Visual Studio Code

Office Add-ins run inside an Office application and can interact with contents of the Office document using the rich JavaScript API.

An Office add-in is composed of a manifest.xml file and your web app.

Under the hood, an Office Add-in is just a web app that you can host anywhere. Using a manifest.xml file, you tell the Office application where your web app is located and how you want it to appear. The Office application takes care of hosting it within Office.

Create a new Office Add-in project

Before you can create an Office Add-in, you must set up your development environment. To assist you with tool installation, see Set up your development environment.

Once you have your tools installed, you can create a basic add-in for Excel, OneNote, Outlook, PowerPoint, Project, or Word by completing a 5-minute quick start. These quick starts use the Yeoman Generator for Office Add-ins (also called "Yo Office") to create a Node.js Office Add-in project that can be managed with Visual Studio Code (VS Code).

Use Visual Studio Code to develop your Office Add-in

Visual Studio Code is a great tool to help you develop your custom Office Add-ins, regardless of whether the add-ins run in web clients, Windows, mobile platforms, or on macOS!

Get started

To open your add-in project in VS Code, navigate to the root directory of your add-in project and enter the following on the command line.

The manifest.xml file of an Office Add-ins project in Visual Studio Code

Within your project, you can view and configure your manifest, HTML, JavaScript or TypeScript, and CSS files to define your add-in. To learn more about developing Office Add-ins in VS Code, refer to Develop Office Add-ins with Visual Studio Code.

Debug your add-in

Debugging your add-in’s client-side JavaScript code varies based on your development environment. To assist you with debugging on certain platforms, see Overview of debugging Office Add-ins.

If you are using Node.js or ASP.NET Core for server-side logic to support your Office Add-in, refer to the Debugging page to configure VS Code for debugging either of these runtimes.

Sideload your add-in for testing

Sideloading allows you to test your add-in to see how it will appear and operate. Yo Office takes care of building your add-in project and sideloading it in Office. To sideload your add-in, navigate to the root directory of your project and run the following from a command line.

You can also manually sideload your add-in by using one of the following options:

  • For Excel, OneNote, PowerPoint, and Word, follow the instructions in Sideload an Office Add-in in Office on the web manually.
  • For Outlook, follow the instructions in Sideload Outlook add-ins for testing.

Publish your add-in

Deploying and publishing your add-in allows you to distribute it to users publicly or within your organization. Once you’re ready to publish your add-in for others to use, you can publish it directly through VS Code using the Azure Storage extension. For guidance on this process, refer to Publish an add-in developed with Visual Studio Code.

To learn more about the various Office Add-ins deployment methods, see Deploy and publish Office Add-ins.

Next steps

Check out the other pages on the VS Code site to find out how you can use more capabilities of the editor when creating custom Office Add-ins:

    — You can write Office Add-ins in many languages. Find out what VS Code has to offer. — Just starting out with VS Code? This is worth reviewing. — Learn about the powerful VS Code editor.

Common questions

Can I create an Office Add-in with the generator and use VS Code regardless of the language or client-side framework?

Yes, you can. You can use pure HTML, Angular, Ember, React, Aurelia. anything you like!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *