Как подключить библиотеку excel в visual studio

0 / 0 / 0

Регистрация: 26.11.2016

Сообщений: 15

1

02.12.2016, 21:32. Показов 38793. Ответов 8


Студворк — интернет-сервис помощи студентам

Добрый день!

Просьба подсказать, как добавить Microsoft.Office.Interop.Excel в Visual Studio 2015.

Спасибо.



0



213 / 209 / 146

Регистрация: 20.11.2014

Сообщений: 1,161

02.12.2016, 22:07

2



0



71 / 68 / 46

Регистрация: 02.12.2015

Сообщений: 890

Записей в блоге: 1

02.12.2016, 22:21

3

У меня поэтому пути расположен dll: C:WindowsassemblyGAC_MSILMicrosoft.Office.Inte rop.Excel15.0.0.0__71e9bce111e9429c



1



906 / 663 / 318

Регистрация: 23.10.2016

Сообщений: 1,540

02.12.2016, 22:38

4

В обозревателе решений ПКМ по «ссылки» -> Добавить ссылку -> Сборка -> Расширения -> Microsoft.Office.Interop.Excel



1



0 / 0 / 0

Регистрация: 26.11.2016

Сообщений: 15

03.12.2016, 00:50

 [ТС]

5

У меня нет такого в обозревателе решений в «ссылках».

Добавлено через 15 минут
Разобрался. Спасибо!



0



0 / 0 / 0

Регистрация: 05.12.2018

Сообщений: 1

10.07.2020, 14:00

6

Ну раз разобрался, то сообщил бы как?



0



chumich

2079 / 1232 / 464

Регистрация: 20.12.2014

Сообщений: 3,237

10.07.2020, 19:20

7

Цитата
Сообщение от TilmatPirat
Посмотреть сообщение

сообщил бы как?

В меню студии: Сборка -> Добавить ссылку.
В открывшемся Менеджере ссылок: СОМ -> Библиотеки типов -> Microsoft Exxcel 12.0 Object Library (у вас может быть 13.0,14.0,15.0 и т. д. — в зависимости от вашего пакета офиса) — поставить галочку.
И далее в коде добавить соответствующий using. Например, так, чтобы не писать в коде Microsoft.Office.Interop.Excel перед каждым объектом:

C#
1
using Excel = Microsoft.Office.Interop.Excel;



5



0 / 0 / 0

Регистрация: 12.07.2021

Сообщений: 58

29.12.2021, 20:02

8

Цитата
Сообщение от chumich
Посмотреть сообщение

В меню студии: Сборка -> Добавить ссылку.

У меня находится в меню студии: Проект-> Добавить ссылку. А дальше уже как описано выше.
Пришлось поискать, так что может пригодится кому



0



Фрилансер

761 / 458 / 146

Регистрация: 06.01.2017

Сообщений: 4,817

29.12.2021, 20:36

9

Цитата
Сообщение от nat_s
Посмотреть сообщение

У меня находится в меню студии: Проект-> Добавить ссылку. А дальше уже как описано выше.
Пришлось поискать, так что может пригодится кому

в большинстве случаев Microsoft.Office.Interop не нужен)
так что вряд-ли)



0



I had developed a system that deals with excel sheets in 2006 using MS VS 2005. Now, I can not use the same reference with MS VS 2012.

var app = new Microsoft.Office.Interop.Excel.Application();
Workbooks wbs = app.Workbooks;

abatishchev's user avatar

abatishchev

97.3k85 gold badges297 silver badges432 bronze badges

asked Mar 8, 2013 at 2:52

Moe_Al's user avatar

2

Use NuGet (VS 2013+):

The easiest way in any recent version of Visual Studio is to just use the NuGet package manager. (Even VS2013, with the NuGet Package Manager for Visual Studio 2013 extension.)

Right-click on «References» and choose «Manage NuGet Packages…», then just search for Excel.

enter image description here


VS 2012:

Older versions of VS didn’t have access to NuGet.

  • Right-click on «References» and select «Add Reference».
  • Select «Extensions» on the left.
  • Look for Microsoft.Office.Interop.Excel.
    (Note that you can just type «excel» into the search box in the upper-right corner.)

VS2012/2013 References


VS 2008 / 2010:

  • Right-click on «References» and select «Add Reference».
  • Select the «.NET» tab.
  • Look for Microsoft.Office.Interop.Excel.

VS 2010 References

answered Mar 8, 2013 at 2:58

Grant Winney's user avatar

Grant WinneyGrant Winney

64.7k12 gold badges114 silver badges164 bronze badges

3

You can also try installing it in Visual Studio via Package Manager.

Run Install-Package Microsoft.Office.Interop.Excel in the Package Console.
This will automatically add it as a project reference.

Use is like this:

Using Excel=Microsoft.Office.Interop.Excel;

MJH's user avatar

MJH

2,2817 gold badges17 silver badges20 bronze badges

answered Dec 31, 2016 at 8:22

CYCLONE's user avatar

CYCLONECYCLONE

5414 silver badges5 bronze badges

0

If you have VS 2013 Express and you cant find Microsoft.Office namespace, try this (‘Microsoft Excel 12.0 Object Library’ if you want to use Office 2007)

enter image description here

answered Apr 20, 2015 at 8:37

Muflix's user avatar

MuflixMuflix

5,77015 gold badges72 silver badges150 bronze badges

1

Building off of Mulfix’s answer, if you have Visual Studio Community 2015, try Add Reference… -> COM -> Type Libraries -> ‘Microsoft Excel 15.0 Object Library’.

answered Nov 15, 2016 at 18:08

Daniel.Veneziano's user avatar

0

Instead of early binding the reference, there’s an open source project called NetOffice that abstracts this from your project, making life much easier. That way you don’t have to rely on your users having a specific version of Office installed.

NetOffice Codeplex site.

answered Jun 11, 2015 at 14:24

LawMan's user avatar

LawManLawMan

3,4491 gold badge28 silver badges32 bronze badges

You have to check which version of Excel you are targeting?

If you are targeting Excel 2010 use version 14 (as per Grant’s screenshot answer), Excel 2007 use version 12 . You can not support Excel 2003 using vS2012 as they do not have the correct Interop dll installed.

answered Apr 1, 2013 at 5:09

mas_oz2k1's user avatar

mas_oz2k1mas_oz2k1

2,8513 gold badges33 silver badges41 bronze badges

Go to Visual Studio Installer under Individual Components and click ‘Office Developer Tools for Visual Studio. This solved it for me after lots of headaches.

Go to Visual Studio Installer under Individual Components and click 'Office Developer Tools for Visual Studio'

answered Jul 28, 2022 at 14:34

Dan's user avatar

DanDan

1741 gold badge2 silver badges10 bronze badges

  • #1

Добавление сборки Microsoft.Office.Interop.Excel

Пошаговое руководство, с помощью которого вы сможете добавить сборку Microsoft.Office.Interop.Excel.dll, предназначенную для работы с Excel файлами, в свой проект.

1. Перейдите в окно Solution Explorer.

c-shpargalka-dlja-raboty-s-papkami-i-podpapkami_1.png

2. Найдите пункт References и нажмите на нём правую кнопку мыши.
3. В появившемся контекстном меню выберите пункт Add Reference.

kak-dobavit-sborku-microsoft-office-interop-excel_1.png

4. В окне Reference Manager выберите пункт Assemblies -> Extensions.
5. Найдите сборку Microsoft.Office.Interop.Excel, после чего выберите ее, установив рядом с ней галочку.

kak-dobavit-sborku-microsoft-office-interop-excel_2.png

6. Нажмите на кнопку с надписью «OK», чтобы добавить сборку в проект.

kak-dobavit-sborku-microsoft-office-interop-excel_3.png

7. Для удобства работы с членами и типами добавьте следующую строку:
using Microsoft.Office.Interop.Excel;
8. Если после добавления сборки или во время работы у вас возникает конфликт имен с типами или членами других сборок, то для решения данной проблемы вы можете создать псевдоним:
using Excel = Microsoft.Office.Interop.Excel;

kak-dobavit-sborku-microsoft-office-interop-excel_4.png

RRS feed

  • Remove From My Forums
  • Вопрос

  • Hi,

    I’m using Visual Studio 2017 Community edition with Windows 10 and I can’t seem to create a reference to Microsoft.Office.Interop.Excel which I need in order to be able to use C# to create a spreadsheet from a SQL statement that will then open up in Excel.
      Is this not available in the community edition or is there something else I am supposed to use?

    Thanks.

    • Изменено
      JunkBondster
      8 июня 2017 г. 14:16

Все ответы

  • Hi,

    I’m using Visual Studio 2017 Community edition with Windows 10 and I can’t seem to create a reference to Microsoft.Office.Interop.Excel which I need in order to be able to use C# to create a spreadsheet that will open up in Excel.   Is this not available
    in the community edition or is there something else I am supposed to use?

    Thanks.

    • Объединено
      Wendy ZangMicrosoft contingent staff
      9 июня 2017 г. 2:39
      deplicate

  • https://social.msdn.microsoft.com/Forums/office/en-US/home?category=officedev

    You should post to the above forum.

  • Hello,

    You should be able to «add reference», select «Assemblies», press the «Browse» button, traverse to a path along this line (most likely close to your machine but slightly different)

    C:Program Files (x86)Microsoft Visual Studio 14.0Visual Studio Tools for OfficePIAOffice15

    Then you should see to select


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via
    my MSDN profile but will not answer coding question on either.
    VB Forums — moderator

    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Предложено в качестве ответа
      Chenchen Li
      9 июня 2017 г. 2:00

  • I dont have office tools under Visual Studio. I have Libra Excel How do I get dll for that

    • Изменено
      Seema716
      25 апреля 2019 г. 19:53

  • Had the same question, finally figured it out.

    1. Go to the Visual Studio Installer

    2. In the Installer, click the Modify Button:

    3. Go to the Individual Components tab and click: Visual Studio Tools for Office (VSTO)

    4. Click Modify and let it install.

    5. Open your Visual Studio project, go to Assemblies, in the search box type in office, and choose: Microsoft.Office.Interop.Excel.

    6. On top of the module, add: Imports Microsoft.Office.Interop.Excel

    • Предложено в качестве ответа
      BIManish
      13 ноября 2019 г. 9:18

  • Hi Manish,

    I did the steps you mentioned, it worked for me.

    Thank you

    Neelima

Давайте научимся быстро и просто создавать и записывать файлы Excel с помощью visual studio c#. Наше самое простое приложение Windows Forms будет брать из текстбокса текст и заносить его в первую ячейку. Статья написана специально для Сергея =).

Начать необходимо с подключения библиотеки Microsoft.Office.Interop.Excel. Выглядеть это должно так:

Если у вас при открытии обозревателя решений – Ссылки – правая кнопка – Добавить ссылку – Сборки – в списке нет Microsoft.Office.Interop.Excel, то добавьте её через Nuget. Проект – управление пакетами NuGet – в строке поиска Excel:

Теперь создайте новый проект Windows Forms и на форму закиньте текстбокс и кнопку. На кнопки кликните два раза, откроется исходный код. В самом верху допишите следующее:

using Excel = Microsoft.Office.Interop.Excel;

А в методе button1_Click замените так:

private void button1_Click(object sender, EventArgs e)
        {
            string fileName = "D:\temp\test.xls";

            try
            {
                var excel = new Excel.Application();

                var workBooks = excel.Workbooks;
                var workBook = workBooks.Add();
                var workSheet = (Excel.Worksheet)excel.ActiveSheet;

                workSheet.Cells[1, "A"] = textBox1.Text;

                workBook.SaveAs(fileName);
                workBook.Close();
            }
            catch (Exception ex) {
                MessageBox.Show("Ошибка: "+ ex.ToString());
            }

            MessageBox.Show("Файл "+ Path.GetFileName (fileName) + " записан успешно!");

        }

Вот, собственно говоря и все. Текст из текстбокса запишется в ячейку A1. Обратите внимание, что папка temp на диске уже должна существовать.

Дополнение. Прочитать первую ячейку

Это тоже просто:

 string fileName = "D:\temp\test.xls";

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;

string temp = (string)(xlRange.Cells[1, 1] as Excel.Range).Value2;// 1 1 - адрес 1-й ячейки
MessageBox.Show(temp);


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегизаметки, си шарп, excel

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Как подключить базу данных sql к excel
  • Как подключить word на телефон
  • Как подключить word на ноутбуке
  • Как подключить word в visual studio
  • Как подключить word бесплатно

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии