Visual studio excel
Работа с Excel с помощью C# (Microsoft.Office.Interop.Excel)
Оставляю заметку по работе с Excel с помощью C#.
Привожу фрагменты кода, которые искал когда-то сам для работы с Excel документами.
Наработки очень пригодились в работе для формирования отчетности.
Прежде всего нужно подключить библиотеку Microsoft.Office.Interop.Excel.
Visual Studio здесь довольно старой версии. Если у вас версия новая, отличаться будет только вид окна.
Далее создаем псевдоним для работы с Excel:
using Excel = Microsoft.Office.Interop.Excel;
Расстановка рамок.
Расставляем рамки со всех сторон:
Цвет рамки можно установить так:
Выравнивания в диапазоне задаются так:
Формулы
Определим задачу: получить сумму диапазона ячеек A4:A10.
Для начала снова получим диапазон ячеек:
Excel.Range formulaRange = sheet.get_Range(sheet.Cells[4, 1], sheet.Cells[9, 1]);
Далее получим диапазон вида A4:A10 по адресу ячейки ( [4,1]; [9;1] ) описанному выше:
string adder = formulaRange.get_Address(1, 1, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
Теперь в переменной adder у нас хранится строковое значение диапазона ( [4,1]; [9;1] ), то есть A4:A10.
Выделение ячейки или диапазона ячеек
Так же можно выделить ячейку или диапазон, как если бы мы выделили их мышкой:
Авто ширина и авто высота
Чтобы настроить авто ширину и высоту для диапазона, используем такие команды:
Получаем значения из ячеек
Чтобы получить значение из ячейки, используем такой код:
Добавляем лист в рабочую книгу
Чтобы добавить лист и дать ему заголовок, используем следующее:
Добавление разрыва страницы
Сохраняем документ
Как открыть существующий документ Excel
Комментарии
При работе с Excel с помощью C# большую помощь может оказать редактор Visual Basic, встроенный в Excel.
Для этого в настройках ленты надо добавить пункт «Разработчик». Далее начинаем запись макроса, производим действия и останавливаем запись.
Далее заходим в редактор Visual Basic и смотрим код, который туда записался:
В данном макросе записаны все действия, которые мы выполнили во время его записи. Эти методы и свойства можно использовать в C# коде.
Данный метод так же может оказать помощь в формировании относительных формул, например, выполнить сложение чисел, находящиеся слева от текущей ячейки на 4 столбца, и т.п. Пример:
Так же во время работы может возникнуть ошибка: метод завершен неверно. Это может означать, что не выбран лист, с которым идет работа.
Rapid Application Development / Advanced Excel Development
Visual Studio Excel Development
There is much more to working with Excel from Visual Studio than just VSTO. Here’s a summary table of the main design patterns and the type of VS project to use.
Here is the powerpoint presentation from the DDD2 community event at Microsoft. The presentation introduces these design patterns and the types of Visual Studio project to use to create each one. It also covered what a COM Shim is and why you need them, and gave some potential reasons to use .net for Excel developments. The VSTO Demo was VS2005RC the COM add-in and the Automation Add-in were VS2003.
As of summer 2008, the Excel/.net story is still less than compelling, although it is improving all the time. At this time the Codematic view is the 2008 VSTO dependencies are very real barrier to adoption for our clients. Standalone exes created in .net can however work extremely well, even if automating Excel.
COM Add-ins
COM Add-ins are found here:
.net Worksheet Functions
Here is the C# source code for a worksheet function project. You need to create a class library project and swap the contents of that file for this file — cut and paste everything within the namespace is probably the easiest. You then need to set project properties to register for COM interop, and set Excel as the Debug application and run. You will also need to load the addin in Excel by picking it from the list of automation add-ins.
If you want the full gory details of creating your own custom Visual Studio project like this:
then get in touch. Warning — not for novices! If there is enough interest I may create an installation routine — but that’s doubtful given the poor performance of .net worksheet functions. This class is based on the work of Eric Carter in Visual Studio Tools for Office, be sure to buy that book (and read it) if you are interested in this area.
.net Worksheet Function Performance
Here is a performance table for a moderately complex array formula I converted to various types of Visual Studio (2003) project:
Here is the worksheet function that was converted (it returns the last non zero value from a list of 100 values):
If you would like the full set of projects to play with then let us know. The C++ one was written with the help of XLL+ from Planatech so you will need a demo copy of that. In fact you can download a Zip with an instruction doc, a test workbook, and the VB6 VBA and C# source code here (1.5Mb). You will need Visual Studio 6 for the VB version and 2003 for the C# one (it may work in other versions — let us know).
All the programmed solutions benefited from using a specific algorithm suited to the problem. The performance difference would be quite different for any other problem. The likely outcome being Excel and C++ much closer and VBA/VB6 further behind. C# unfortunately, would probably never make the grade.
The VBA one was compiled, and the IDE closed before running. The VB6 version had all speed optimisations set. I did not bother with a VB.net version as there seems no reason to believe it would be materially faster than C#.
The C# code is significantly different to the other code as it needs an Excel reference to be able to understand the range that is passed in. In VB6 and VBA that is treated as a variant, and looped through in the normal way. However, simply adding 2 doubles (ie no Excel objects) in the above manner takes 30 seconds in C#, so its not just the Excel reference, if at all (Excel comparison time? 0 seconds rounded to 0 decimal places!).
The only fair conclusion from this analysis is that it is very expensive to pass through the Primary Interop assemblies for Office 2003. If a worksheet function is only used a few times then the benefits of .net may outweigh the speed penalty, but for the type of use I see, .net is not currently appropriate. This issue has been raised with Microsoft and they are investigating it.
For now, and probably for a good while into the future, the only viable technology to implement most worksheet functions seems to be C++. And conveniently enough XLL’s are also simple to deploy, requiring no registry access, no VB runtimes, and no .net framework. They also work with all versions of Excel from 97 onwards.
And guess what? Codematic can help you write your custom worksheet functions in C++.
We can work from scratch, a paper spec, a complex worksheet function, a VB/VBA function, even old XLM, whatever, we’ll convert it to a C++ XLL.
If you require any more information please get in touch.
Visual studio excel
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору Некоторое время назад задался целью найти готовую библиотеку для чтения/записи файлов .xls и .xlsx без установленного приложения Excel
Если Excel установлен, то кажется, что всё просто. Однако: 1) он должен быть установлен 2) есть разница работы с разными версиями офиса — зависим от версии 3) запись больших таблиц работает очень медленно. и т.д., на этом проблемы не заканчиваются.
После серьёзного изучения вопроса, понял, что действительно стоящего варианта — не найдено. Существует несколько библиотек, как свободных, так и платных. Но ни те, ни другие — не удовлетворяют. С чтением таблиц — проблем нет, это делается, например, через MS Jet. А вот запись, тем более — с форматированием, вызывает вопросы.
Задача «минимум» для такой библиотеки:
1) запись файла (например, .xlsx) из dataset — одним вызовом.
2) автоматический подбор ширины столбцов по содержимому (AutoFit)
3) выбор шрифта (хотя бы одного на весь файл) и его размера
4) установка автофильтра на всё содержимое
т.е. получаем файл, готовый к просмотру и к обработке данных без лишних телодвижений вручную. Желательно, чтобы использование библотеки выглядело как можно более лаконично в коде.
Предлагаю обсудить, кто чем пользуется, какие библиотеки рекомендует.
Пробовал EPPlus 2.9, GemBox.Spreadsheet. На крайний случай сгодится, но не очень.
Во многих библиотеках присутствует один и тот же глюк: формат «# ##0,##» до Excel доходит как «# ##0,##».
Generates Excel files from WinForms, WebForms ASP.NET, PocketPC applications, webservices on the fly and fast with FlexCel Studio for .NET
Native .NET components (no additional OLE/dlls required) allowing to read, create and modify native Excel .XLS and .XLSX files without needing to have Excel installed.
Supported Excel 97 .XLS file format and Excel 2007/2010 .XLSX format
Native PDF file export
Exceptionally fast and solid hand tuned .XLS & .XLSX engine capable of generating thousands files per minute.
Able to modify .XLS files and keep almost everything existing on the original file, from macros to activex objects.
Recalculation of more than 200 Excel functions.
Ability to read and write encrypted .XLS files.
Completely written in C# 100% managed code, with NO interop and NO p/invokes!
Runs on .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, Mono and the .NET Compact Framework (xlsx support requires .NET 3.5).
Templates can be stored inside your executable file, in a database or in any place from where you can access it as a stream.
Extensive API is available with which you can programmatically write and read files, with formatting info, images comments, etc.
Export to HTML in HTML 4.01 strict or XTHML 1.1 and fully standards compliant
Report Engine that allows to create complex reports using Excel as your report designer, so your final users can modify them. You can use images/comments/conditional formats/merged cells/pivot tables/charts and almost anything you can think of on those reports.
using System.IO;
using System.Globalization;
using System.Drawing;
using FlexCel.Core;
using FlexCel.XlsAdapter;
public void CreateAndSaveFile()
<
XlsFile xls = new XlsFile(true);
CreateFile(xls);
//Save the file as XLS
xls.Save(openFileDialog1.FileName);
>
public void CreateFile(ExcelFile xls)
<
xls.NewFile(1); //Create a new Excel file with 1 sheet.
xls.ActiveSheet = 1; //Set the sheet we are working in.
>
Все имеется. Куча примеров.Могу кинуть на обменник FS. правда немного староват дистр.
Вообще-то не помешает, по крайней мере поизучать. Я сам кое-что попробовал, но форматирование — не прошло, вообще. Не понял пока что не так.
Кстати, YuriyRR, может ты заодно знаешь почему все библиотеки (может не все, но всё что я пробовал — это много) корёжат формат, заданный строкой, я тут уже выше писал:
Вероятно ожидают увидеть формат в английской локали, где в качестве десятичного разделителя используется тчк, а не зпт. Соответственно эскейпят все прочие символы. Или, как вариант, у тебя на машине локаль неправильная стоит.
Добавлено:
Когда-то давно делал репорты в excel на asp.net вообще без библиотек:
— сохраняешь готовый отформатированный пример репорта с одной строчкой в xml
— копи-пастишь как есть в aspx
— находишь строчку с данными и делаешь итерацию по датасету
— бинго! — красивый репорт за 15 мин
Зпт. у них активно используется, как разделитель групп разрядов
Правильная, хотя может быть и нестандартная (что тут вообще стандарт?):
Десятичный разделитель — зпт.
Разделитель групп разрядов — пробел
Возможно англоязычные разработчики не догадываются, что русские могут использовать запятую таким странным образом
Имеет смысл проверить на машине с en-US и с английским же форматом, а потом уже смотреть где валится на русской, да еще и с хитрой локалью.
Visual studio excel
Comments and Discussions
Nearly thirteen years since this article & code was first posted, shows that good work is never out of date — found it by accident via a Google search and it was just what I needed.
I’m very much obliged to you.
I have little patience with scientists who take a
board of wood, look for its thinnest part, and drill a
great number of holes where drilling is easy.
I have little patience with scientists who take a
board of wood, look for its thinnest part, and drill a
great number of holes where drilling is easy.
when I am using
string[] A4D4 = excel.GetRange(«A4:L4»);
am getting arrayOutOfIndexBound exception.
Why is this.
How to resolve this issue?
I just start learning coding; therefore, I am very new. I want to write a program that read all the tabs in the excel. However, I don’t know how to do it. Can someone please help?
There is a very good article that provides functionality to achive the same (Reading frm & Writing to excel). Though the USP of the article is its cleanup approach, but it will help you do the excel manipulation with ease. The article can be found at
you can easily read Excel to DataTable with this Excel C# / VB.NET component and then you can easily read cell values through DataTable.
Here is an Excel C# sample:
I am trying to determnine if VS 2008 Excel Workbooks/Templates are the appropriate tool for something.
I want users to be able to enter structured data (columns and rows) offline and then later connect to the internet and upload it.
Maybe they visit my web site and click a button to have an excel file emailed to them . or they download the excel file directly.
I might use excel forms to ease data entry and save the actual «database» (columns/rows) in a Sheet.
Once they are done, they would click a button in the spreadsheet and upload the data (maybe have it communicate to a web service).
> If I write code using visual studio does it become part of the excel file or is the code in a separate file?
> What do I deploy in a shared hosting arrangement?
> When doing the data entry in the spreadsheet, do they have to have an internet connection?
Is an appropriate use of this tool? Or is it more of a reporting tool for graphs, etc?
Hi i added the references to microsoft.office.core and microsoft.office.interop.excel and in the codefile
using Office = Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
but if i go with the mouse over office it says: cannot resolve symbol «office»
also intellisense does not work if i type eg. office.
can you please help me
The problem is mentioned below..
I’m writing a C#.Net app which will populate an Word Document. The app references Word using COM.
I have Office 2003 and 2007 on my machine and the application refers to both version dlls (12 .0 and 11.0 of Microsoft.Office.Interop.Word) is built and deployed. The server where application is deployed also contains both Office
2003 and 2007.
But while working with the application, always Word 2007 is considered.
In the Solution Explorer view, I see the properties for the Word Reference set to:
Microsoft.Office.Interop.Word :
Description:Microsoft Excel 11.0 Object Library
Path: C:WINDOWSassemblyGACMicrosoft.Office.Interop.Word12.0.0.0__71e9bce111e9429cMicrosoft.Office.Interop.Word.dll
It’s saying it’s Word 11, but then references the Word 12 interop libraries, above. I’ve removed the reference and added it again and it’s still the same.
Any suggestions as to how I fix this? I want to refer to MS Office 11.0.0.0 for 2003 files and MS Office 12.0.0.0 for 2007 related files in the same project.
Ive created an appl. that reads and extract column data from several excel sheets and pasted them onto a new excel sheet.
excelWorkbook = excelApp.Workbooks._Open (filePath,
0, true, 5, «», «», false, Excel.Window ,»»,
true, false, 0, true, false, false);
In the above statement,an error occued saying:
«‘Microsoft.Office.Interop.Excel.Window’ is a ‘type’, which is not valid in the given context d:WindowsApplication1WindowsApplication1Form1.cs 135 50 WindowsApplication1
Hi,
i have a column that contains cell like this
string1 — string2 etc..
I need to set differents colours for differents strings. This is a console application (post process of a xls generation by 3th part).
I’m using
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Excel;
.
private static Microsoft.Office.Interop.Excel.Application excel = null;
private static Microsoft.Office.Interop.Excel.Workbook wb = null;
private static Microsoft.Office.Interop.Excel.Worksheet wsheet = null;
private static Range range = null;
.
excel = new Microsoft.Office.Interop.Excel.Application();
wb = excel.Workbooks.Open(MyFileNameXls, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
wsheet = wb.ActiveSheet;
range = wsheet.UsedRange;
..in a loop..
((Range)range.Cells[myStartRow, myColumn]).Select();
((Range)range.Cells[myStartRow, myColumn]).Interior.ColorIndex = 1;
((Range)range.Cells[myStartRow, myColumn]).Interior.Pattern = 1;
.
Here i need to set the colour of the substring of the ActiveCell..
.
Please help me!
Bye & thanks a lot
Gigi
Автоматизация excel с помощью Visual Studio
У меня есть очень большая таблица excel, которую я отправляю своим клиентам, чтобы внести изменения в свои продукты, и они отмечают изменения. Когда электронная таблица возвращается, я должен проверить изменения с помощью моего основного листа. Существует уникальный код для продукта, но новый продукт помечается как новый, пока я не выделю код. Я делаю это в excel, потому что мои клиенты чувствуют себя комфортно с excel. Я ищу способ автоматизировать весь этот процесс, но не знаю с чего начать. Я использую Visual studio Ultimate 2010 и имею SQL Server Standard Edition. возможно ли иметь приложение, которое захватывает считывает excel и помещает его в базу данных и проверяет или проверяет, как это происходит. Затем выделяет первичные ключи и создает отчет?
4 Ответов
Вы захотите проверить автоматизацию Excel из библиотеки MSDN. Это поможет вам начать с Excel стороны. Затем просто работайте с базой данных в стандартном консольном приложении и импортируйте.
Если вы хотите работать в библиотеке C#,, используйте библиотеку Microsoft.Office.Interop.Excel. Вы можете импортировать ссылку, если у вас установлен excel. Это может оказаться полезным. Что касается базы данных, я не могу вам помочь.
Хорошо, как насчет преобразования таблицы Excel в XML на вашем конце, а затем переместите данные в свою базу данных, взгляните на этот LINK и этот LINK и этот LINK тоже.
Это всего лишь идея, а не полное разработанное решение, но вы можете использовать OleDb, чтобы добраться до вашего файла excel и прочитать его содержимое, как это было в таблице базы данных.
Затем вам нужно подключиться к вашей основной базе данных (SqlServer) и применить логику, необходимую для ‘merge’ одного источника данных в другой
Теперь все ваши данные из первого файла листа excel загружаются в память внутри объекта datatable
Похожие вопросы:
Мне было любопытно, можно ли это сделать с помощью PowerShell. Лично я хотел бы автоматизировать: добавление существующего локального веб-сайта IIS в решение Я видел, как один человек пытался.
надеюсь, кто-то имел подобную проблему и сможет помочь. Visual Studio 2010 У меня есть xll-файл, созданный с помощью excel-DNA и C#. я могу прикрепить его к электронной таблице excel с загруженным.
Я хочу автоматизировать запущенный экземпляр Visual Studio с MATLAB, подобно тому, как это было сделано в этой статье в C#., я знаю, как создать новый экземпляр с помощью hCOM =.
Я поддерживаю приложение Winform, развернутое на рабочем столе через ClickOnce. В настоящее время я использую мастер публикации Visual Studio, чтобы сделать новую версию доступной. Я хотел бы.
Я разрабатываю отчеты из Visual Studio 2010 с помощью .расширение rdlc. Существует требование, когда я должен экспортировать все отчеты в один файл excel в виде вкладок. Когда я экспортирую отчеты в.
У меня есть Excel addin, написанный в VBA, который перебирает используемый диапазон листа и манипулирует значениями ячеек. Это простое дополнение, но теперь требования пользователей изменились, и я.
Silverlight Excel Автоматизация Завода API Документация Привет Im с помощью Excel Automation Factory для экспорта данных из silverlight в excel. Проблема в том, что я не могу найти документацию по.
Я пытаюсь открыть excel workbook 2003 с помощью VSTO. но я получаю ошибку снова снова, как Проект не может быть создан, так как надстройка приложения работает неправильно и, возможно, была.
У меня есть проект Visual Studio 2015 DB для SQL Server DB, где я могу выполнить сравнение схем/сравнение данных и вернуть проект в GIT вручную. Я хотел автоматизировать этот полный процесс.
Я разработал надстройку Excel с помощью Visual Studio 2010. Когда я отлаживаю свой проект, надстройка загружается в Microsoft Excel 2010. Теперь я также установил Office 2013 на своем компьютере, и.