Как создать файл excel в vb net

Excel Sheet in VB.net – VB.net makes it possible for the COM object model of Microsoft Excel 2010 to work with your application.

To use this interoperability in your application, you need to add the namespace Microsoft.Office.Interop.Excel to your Windows Form Application.

Today I will teach you about How to Create an Excel File Using VB.net. Create an Excel File Using Visual Basic.Net provides support for interoperability between the COM object model of Microsoft Excel and your application.

Table of contents

  • What is Visual Basic’s purpose?
  • What is Excel Sheet in VB.net?
  • How to Create an Excel File Using VB.net
  • Program Output:
  • Download the Source Code:
  • Summary
  • Readers might read also:
  • Inquiries

We have learned how to use the Regular Expression in VB.net in the previous lesson. In this lesson we shall learn How To Write a Program for Excel Sheet in VB.net.

What is Visual Basic’s purpose?

The third-generation programming language was created to aid developers in the creation of Windows applications. It has a programming environment that allows programmers to write code in.exe or executable files.

They can also utilize it to create in-house front-end solutions for interacting with huge databases. Because the language allows for continuing changes, you can keep coding and revising your work as needed.

However, there are some limits to the Microsoft Visual Basic download. If you want to make applications that take a long time to process, this software isn’t for you.

That implies you won’t be able to use VB to create games or large apps because the system’s graphic interface requires a lot of memory and space.

Furthermore, the language is limited to Microsoft and does not support other operating systems.

In Excel documents, a Worksheet is a group of cells that are set up in rows and columns. It is the part of the computer you use to enter data.

Each worksheet has 1048576 rows and 16384 columns, making it a big table that you can use to organize information.

So let’s get started:

How to Create an Excel File Using VB.net

Steps in Creating an Excel Application from VB.net.

Time needed: 5 minutes.

Creating an Excel Application from VB.net

  • Step 1: Create New Project

    First is open the Visual Basic, Select File on the menu, then click New and create a new project.

    new project

  • Step 2: Name your Project

    Then a New Project Dialog will appear. You can rename your project, depending on what you like to name it. After that click OK
    rename project

  • Step 3: Design your Windows Form

    Then design your form like this just like what I’ve shown you below
    Add a Button from the toolbox.
    Design Windows Form

  • Step 4: Add Reference

    After that, Add a Reference to Microsoft Excel Object Library to your project.
    To do this:
    *Select add reference from the project menu.
    add reference

  • Step 5: Locate Microsoft Excel Object Library

    On the COM tab, Locate Microsoft Excel Object Library and then click select.
    Locate Microsoft Excel Object Library

  • Step 6: Add Following Code

    Double click the code window and add this following code to the top of Public Class Form1.

    Imports Excel = Microsoft.Office.Interop.Excel

  • Step 7: Double click the Button and add this following code

    Then, Go back to Design View and Double click the Button and add this following code.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim appXL As Excel.Application
    Dim wbXl As Excel.Workbook
    Dim shXL As Excel.Worksheet
    Dim raXL As Excel.Range
    appXL = CreateObject(“Excel.Application”)
    appXL.Visible = True
    wbXl = appXL.Workbooks.Add
    shXL = wbXl.ActiveSheet
    shXL.Cells(1, 1).Value = “FIRST NAME”
    shXL.Cells(1, 2).Value = “LAST NAME”
    shXL.Cells(1, 3).Value = “FULL NAME”
    shXL.Cells(1, 4).Value = “SUBJECTS”
    With shXL.Range(“A1”, “D1”)
    .Font.Bold = True
    .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
    End With
    Dim pupils(5, 2) As String
    pupils(0, 0) = “Markfil”
    pupils(0, 1) = “Baldomero”
    pupils(1, 0) = “Juvy”
    pupils(1, 1) = “Aral”
    pupils(2, 0) = “Andrew”
    pupils(2, 1) = “Braza”
    pupils(3, 0) = “Carlie”
    pupils(3, 1) = “Golez”
    pupils(4, 0) = “Jesriel”
    pupils(4, 1) = “Agita”
    shXL.Range(“A2”, “B6”).Value = pupils
    raXL = shXL.Range(“C2”, “C6”)
    raXL.Formula = “=A2 & “” “” & B2″
    With shXL
    .Cells(2, 4).Value = “English”
    .Cells(3, 4).Value = “Algebra”
    .Cells(4, 4).Value = “Physics”
    .Cells(5, 4).Value = “Trigonometry”
    .Cells(6, 4).Value = “Theology”
    End With
    raXL = shXL.Range(“A1”, “D1”)
    raXL.EntireColumn.AutoFit()
    appXL.Visible = True
    appXL.UserControl = True
    raXL = Nothing
    shXL = Nothing
    wbXl = Nothing
    appXL.Quit()
    appXL = Nothing
    Exit Sub
    Err_Handler:
    MsgBox(Err.Description, vbCritical, “Error: ” & Err.Number)
    End Sub

  • Step 8: Click F5 to run the program.

    Finally, Click F5 to run the program.

Program Output:

Create an Excel File Using Visual Basic.Net
Create an Excel File Using Visual Basic.net

Download the Source Code:

Summary

This article shows how to make an Excel sheet and how to fill a range of cells with a number of different values. This article also shows how to get a range of cells as an array of cells.

Readers might read also:

  • How to Get Total Value in DataGridview Using VB.Net
  • How to Connect Visual Basic.Net to MS Access Database

Inquiries

If you have any questions or suggestions about this Excel Sheet in VB.NET, please let me know just drop a comment below of send me a message on our contact page.


PREVIOUS

Database Access in VB.net

  • Remove From My Forums
  • Question

  • User-748031297 posted

    VWD 2008 Express.  Visual Basic.

    Is it possible to build an Excel workbook from VB code behind an aspx page.  What do I need to do?  Can anyone provide a code sample?  Thanks.

Answers

  • User-748031297 posted

    I needed to use the following to get the Excel 2003 library:

    Imports Microsoft.Office.Interop.Owc11

    and instead of:

    xlApp = New Excel.ApplicationClass  (Which seems to create an Excel 2007 file)

    I used:

    xlApp = New Excel.Application  (Which creates an Excel 2003 file)

    So the whole thing is:

    Imports Excel = Microsoft.Office.Interop.Owc11
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object,_
    	 ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim xlApp As Excel.Application
            Dim xlWorkBook As Excel.Workbook
            Dim xlWorkSheet As Excel.Worksheet
            Dim misValue As Object = System.Reflection.Missing.Value
    
            xlApp = New Excel.Application
            xlWorkBook = xlApp.Workbooks.Add(misValue)
            xlWorkSheet = xlWorkBook.Sheets("sheet1")
            xlWorkSheet.Cells(1, 1) = "http://vb.net-informations.com"
            xlWorkSheet.SaveAs("C:vbexcel.xlsx")
    
            xlWorkBook.Close()
            xlApp.Quit()
    
            releaseObject(xlApp)
            releaseObject(xlWorkBook)
            releaseObject(xlWorkSheet)
    
            MsgBox("Excel file created , you can find the file c:")
        End Sub
    
        Private Sub releaseObject(ByVal obj As Object)
            Try
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
                obj = Nothing
            Catch ex As Exception
                obj = Nothing
            Finally
                GC.Collect()
            End Try
        End Sub
    
    End Class
    
    

     

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

kritjara

65 / 56 / 14

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

Сообщений: 298

1

29.08.2016, 10:32. Показов 5745. Ответов 13

Метки нет (Все метки)


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

на данный момент использую следующий код для создания xls файла и последующего его заполнения

VB.NET
1
2
3
4
5
6
Dim ExcelApp As Excel.Application = CreateObject("Excel.Application")
Dim ExcelBook As Excel.Workbook = ExcelApp.Workbooks.Add
Dim xls As Excel.Worksheet = ExcelBook.ActiveSheet
ExcelApp.Visible = True
 
'цикл, заполняющий файл

но этот вариант плох тем что мне необходимо порой заполнять до 3000 страниц
даже если разбивать на этапы и создавать файлы десятками, то все равно это требует много времени и это при том, что у меня сильный комп
переносил этот вариант на рабочий старый комп (2,2 гц проц, 1 гб озу), то там беда полная, более 7 сек уходит на 1 страницу, и чем дальше тем медленнее, бывает так чтобы оформить пятидесятую страницу, уходит более 30 сек

можно ли создать файл так, чтобы при первом его открытии ячейки уже были заполнены?
также прошу подскажите, может есть возможность сделать так чтобы шрифты/объединениеячеек/выравнивание и прочее тоже можно было изменить, не открывая при этом сам файл



1



Модератор

Эксперт .NET

3878 / 3200 / 482

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

Сообщений: 5,842

29.08.2016, 11:16

2

а если не создавать а хранить шаблон в ресурсах.
далее его отрывать и заполнять пачкой а не построчно в цикле.
тоесть формировать массив строк и сбрасывать потом в ексель?



0



kritjara

65 / 56 / 14

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

Сообщений: 298

29.08.2016, 14:26

 [ТС]

3

файл — это счета к оплате
в счете может быть от 1 до 3 услуг, поэтому счета имеют разные размеры (19, 21 или 23 строки)
к тому же неизвестно какой счет будет первым и сколько их будет вообще
поэтому шаблон мне не подходит

я рассматривал вариант с сохранением данных в буфере обмена, разделял ячейки через табуляцию, потом вставлял в отформатированный пустой excel
работает, но если пользователь вставляет не там где надо, или случайно добавляет/удаляет строки то сразу подозреваю будут «вопли/сопли почему не работает»
к тому же в буфере не могу сохранить большой объем информации, и приходится делать это частями
экономия времени мала

Добавлено через 1 час 45 минут
попробовал еще таким образом, но безуспешно

VB.NET
1
2
3
4
5
Dim ExcelApp As Excel.Application = CreateObject("Excel.Application")
Dim ExcelBook As Excel.Workbook = ExcelApp.Workbooks.Add
Dim xls As Excel.Worksheet = New Excel.Worksheet
' заполняю xls
ExcelBook.Worksheets.Add(xls)

выдается следующаи ошибка
Дополнительные сведения: Невозможно привести COM-объект типа «Microsoft.Office.Interop.Excel.WorksheetClass » к интерфейсному типу «Microsoft.Office.Interop.Excel._Worksheet». Операция завершилась со сбоем, поскольку вызов QueryInterface COM-компонента для интерфейса с IID «{000208D8-0000-0000-C000-000000000046}» возвратил следующую ошибку: Интерфейс не поддерживается (Исключение из HRESULT: 0x80004002 (E_NOINTERFACE)).



0



Модератор

Эксперт .NET

3878 / 3200 / 482

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

Сообщений: 5,842

29.08.2016, 14:29

4

из вашего разъяснения я нн понял структуры самого файла xls… вы б показали пример.

Добавлено через 2 минуты
а ошибка ууазывает на несоотвеьсвие типов. Если вы используете позднее связывание, то типы переменных не нужно ууазывать, дабы не ошибится. Поограмма сама присвоит соответствующий тип каждой.



0



65 / 56 / 14

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

Сообщений: 298

29.08.2016, 14:40

 [ТС]

5

честно скажу, я не профи в программировании, самоучка и неопытен
не все понимаю с ваших слов, например

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

Если вы используете позднее связывание, то типы переменных не нужно ууазывать, дабы не ошибится.

если можно, то в виде кода это показать

и вот файл, который формируетсяКнига.xls



0



Yury Komar

Модератор

Эксперт .NET

3878 / 3200 / 482

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

Сообщений: 5,842

29.08.2016, 16:09

6

не объявляя переменных

VB.NET
1
2
3
Dim ExcelApp = CreateObject("Excel.Application")
Dim ExcelBook = ExcelApp.Workbooks.Add
Dim xls = ExcelBook.Worksheets.Add("New Worksheet")



0



Sklifosofsky

1001 / 857 / 203

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

Сообщений: 982

29.08.2016, 20:37

7

Вот есть некоторые нюансы по производительности при заполнении:
Работу ускорит ExcelApp.Visible = False, а соответственно при этом не будет перерендеринга окна. После заполнения можно включить.
Также с ExcelApp.ScreenUpdating = False. При этом окно не пропадает, но только картинка не обновляется. По завершению переключить на True.
Есть быстрый способ заполнения при передачи двумерных массивов. У меня огромные массивы влетали за секунду

VB.NET
1
2
3
4
5
6
7
8
9
10
  dim arr(2,2) as String
 
        For i As Integer = 0 To 2
            For j As Integer = 0 To 2
                n += 1
                arr(j, i) = n.ToString
            Next
        Next
 
        oSheet.Range("A1").Resize(3, 3).Value  = arr ' вставка начинается с первой ячейки

Попробуйте по экспериментировать с последним вариантом.

Насчет стилей подсказать не могу



2



4278 / 3417 / 827

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

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

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

03.09.2016, 01:02

8

Решил проанализировать скорость формирования документа, который представляет собой список счетов (вариант ТС). Выделяется три блока счетов, которые заполняются из таблицы с базовой информацией и копируются в окончательный документ. Рассмотрены два варианта:
1. С использованием Microsoft.Office.Interop.Excel (формат файла xls)
2. С использованием библиотеки EPPlus (формат файла xlsx)
Получены следующие результаты:

Число счетов Вариант xls (время в сек) Вариант xlsx (время в сек)
20 1.5 0.3
100 4.5 0.6
500 20 2.3
1000 40 4.6

Замечания:
1. Вполне можно ограничиться использованием одного типа блока (неиспользуемая строка остается пустой).
2. Если полученные результаты не устраивают, то от использования формата Excel придется отказаться и формировать счета непосредственно в программе с выводом на печать (в файл). Это конечно достаточно хлопотно.
3. Окончательную компиляцию выполняйте в конфигурации Release.



3



65 / 56 / 14

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

Сообщений: 298

03.09.2016, 16:01

 [ТС]

9

интересный вариант заполнения

тут же остается вопрос, каким способом вы определяли как должен выглядеть счет?
какие и сколько видов услуг? как быть если в счет попадает одноразовая услуга с другим названием?
как быть если услуг более 5 видов? создавать новые готовые блоки и для каждого раза новые (потому что разные услуги)?

и глядя на тот факт что 3000 листов формируются за 5 минут придется подстраиваться под именно этот вариант
в связи с этим прошу Вас ответить еще на пару вопросов
1. за счет чего файл настолько быстро формируется?
2. будет ли работать библиотека на конечной машине (win XP .NET 4.0, MS Office 2003 и 2010)?
3. насколько сильно синтаксис этой библиотеки отличается от VBA?
4. чем лучше эта библиотека, чем та что встроена в VS 2105?



0



4278 / 3417 / 827

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

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

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

03.09.2016, 18:11

10

kritjara,
Как я уже писал, в данном случае меня интересовала скорость заполнения документа типа предложенного вами образца. Какие услуги и сколько их может быть, речи не было, как не было и внятной постановки задачи. Исходя из здравого смысла, могу предположить, что источником информации является база данных, в которой и хранится вся информация по видам и количеству услуг привязанных к конкретному клиенту.
В прилагаемых проектах вид счета определяется тремя шаблонами счета (исходя из приложенного вами образца). Если услуг много? Для начала стоит определить число услуг имеющих максимальную частоту среди всех возможных вариантов. Например, максимальное число услуг для одного клиента 10, а с максимальной частотой – 5. тогда я бы завел три блока шаблона счета: с тремя строками в счете, с пятью и с десятью. Напомню, все имена услуг и их количественные характеристики берутся из базы. Если в базе находим клиента, к которому привязаны две услуги то выбираем шаблон 1 и заполняем первые две строки в счете, третья остается пустой и т.д. сканируем базу по всем клиентам и выбираем подходящий шаблон. То, что в счете могут оставаться пустые строки не является криминалом. Если хотите, чтобы таких счетов было меньше увеличьте число шаблонов.
Отвечу на ваши вопросы:
1. См. проект
2. Если речь идет о EPPlus то Net 4.0 вполне достаточно, при формировании файла MSOffice никак не участвует, т.е. Office может вообще отсутствовать. Но для просмотра файла Excel (7, 10) потребуется (но и в Excel2003 этот файл также можно просмотреть).
3. Этот синтаксис определяется Open XML SDK, хотя какие-то аналогии с Excel VBA, наверное, можно провести.
4. Не понял, о какой встроенной в VS библиотеке идет речь.



0



65 / 56 / 14

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

Сообщений: 298

04.09.2016, 10:09

 [ТС]

11

ovva, правильно ли я вас понял?
под шаблоном имеется ввиду Range отформатированный (с объединенеями ячеек, отрисованными таблицами и заполненной шапкой: реквизиты)
для меня важно динамическое выполнение кода, если я правильно вас понял, то шаблоны можно заставить создаваться кодом

Добавлено через 9 минут

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

4. Не понял, о какой встроенной в VS библиотеке идет речь.

Microsoft.Office.Interop.Excel

не буду загадывать хуже или лучше она чем EPPlus, но ваша разница во времени заполнения xls и xlsx может быть изза разницы форматов, одни и те же табличные данные в разных форматах занимают совершенно разное место на диске

какие явные плюсы об этой библиотеке вы можете привести помимо того что установка офиса не требуется?
и работает ли библиотека с .docx? насколько я понял, то нет, если правильно понял



0



Модератор

Эксперт .NET

3878 / 3200 / 482

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

Сообщений: 5,842

04.09.2016, 10:23

12

kritjara, Microsoft.Office.Interop.Excel это не встроенная в студию библиотека, и она не работает с самим файлом, а работает с объектом программы Excel, а уже эксель работает с вашим файлом, тоесть вы передаете экселю команды, а он уже их выполняет, а вот EPPlus работает с самим файлом, от этого и скорость, будто вы напрямую читаете строки файла и так далее.



1



4278 / 3417 / 827

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

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

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

04.09.2016, 13:14

13

kritjara,
1. Да, см. файл tAccount.xlsx лист Blocks.
2. Непонятно что вы вкладываете в «динамическое выполнение кода». Эти блоки шаблонов можно сформировать и в коде, только зачем. Смысла в этом никакого тем более если вдруг шаблон нужно поменять, то на листе Excel это можно сделать без проблем.
3. Yury Komar, этот пункт уже разъяснил.
4. Форматы xls и xlsx различаются принципиально. Файл xlsx это фактически архив. Вы можете установить у такого файла расширение zip, открыть архив и посмотреть, что в него входит.
5. EPPlus с docx не работает. Но есть другие библиотеки, работающие с этими файлами на той же базовой основе (Open XML), например DocX (http://docx.codeplex.com).



1



174 / 64 / 13

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

Сообщений: 2,648

04.12.2016, 13:40

14

kritjara, я попробовал создать xls файл указанным Вами способом, но у меня ничего не получилось.
Ссылку COM | Microsoft Office 10.0 Object Library подключил. Наверное нужно ещё что-то. С уже созданным файлом xls работать получается, а вот создать его из проекта Windows Form пока не выходит



0



Содержание

  1. How to create Excel file in VB.Net
  2. Excel Library
  3. How to use COM Interop to Create an Excel Spreadsheet
  4. How to create an Excel Document Programmatically
  5. Save Excel file (SaveAs() method)t
  6. How to properly clean up Excel interop objects
  7. VB.Net – Excel Sheet
  8. Создание приложения Excel из VB.Net
  9. Excel Sheet in VB.net – How to Create an Excel File Using VB.net
  10. Table of contents
  11. What is Visual Basic’s purpose?
  12. What is Excel Sheet in VB.net?
  13. How to Create an Excel File Using VB.net
  14. Program Output:
  15. Download the Source Code:
  16. Summary
  17. Vb net создать файл excel
  18. Answered by:
  19. Question
  20. Answers
  21. All replies
  22. VB.Net — Excel Sheet
  23. Creating an Excel Application from VB.Net

How to create Excel file in VB.Net

Automation to Excel allows you to perform actions such as creating a new workbook, adding data to the workbook, or creating charts etc. The following VB.Net code example shows how to use COM interop to create an Excel file. Before going to create new Excel file programmatically in VB.Net, you must have Excel installed on your system for this code to run properly.

Excel Library

In order to access the object model from Visual VB.NET, you have to add the Microsoft Excel 12.0 Object Library to your current project.

Create a new project and add a Command Button to your VB.Net Form.

How to use COM Interop to Create an Excel Spreadsheet

Form the following images you can find how to add Excel reference library in your VB.Net project.

Select reference dialogue from Project menu.

How to create an Excel Document Programmatically

First we have to initialize the Excel application Object in your VB.Net application.

Before creating new Excel Workbook, you should check whether Excel is installed in your system.

Then create new Workbook

After creating the new Workbook, next step is to write content to worksheet

In the above code we write the data in the Sheet1, If you want to write data in sheet 2 then you should code like this.

Save Excel file (SaveAs() method)t

After write the content to the cell, next step is to save the excel file in your system.

How to properly clean up Excel interop objects

Finally, we have to properly clean up Excel interop objects or release Excel COM objects. Here we write a function to clean up the Excel Application, Excel Workbook and Excel Worksheet Objects.

Creating an Excel Spreadsheet Programmatically

Источник

VB.Net – Excel Sheet

VB.Net обеспечивает поддержку взаимодействия между объектной моделью COM Microsoft Excel 2010 и вашим приложением.

Чтобы использовать эту совместимость в вашем приложении, вам необходимо импортировать пространство имен Microsoft.Office.Interop.Excel в ваше приложение Windows Form.

Создание приложения Excel из VB.Net

Давайте начнем с создания приложения Window Forms, выполнив следующие шаги в Microsoft Visual Studio: Файл → Новый проект → Приложения Windows Forms.

Наконец, нажмите OK, Microsoft Visual Studio создаст ваш проект и отобразит следующую форму Form1 .

Вставьте элемент управления Button1 в форму.

Добавьте ссылку на библиотеку объектов Microsoft Excel в свой проект. Для этого –

Выберите Добавить ссылку в меню проекта.

Выберите Добавить ссылку в меню проекта.

На вкладке COM найдите библиотеку объектов Microsoft Excel и нажмите «Выбрать».

На вкладке COM найдите библиотеку объектов Microsoft Excel и нажмите «Выбрать».

Дважды щелкните окно кода и заполните событие Click для Button1, как показано ниже.

Когда приведенный выше код будет выполнен и запущен с использованием кнопки « Пуск» , доступной на панели инструментов Microsoft Visual Studio, появится следующее окно:

При нажатии на кнопку отобразится следующий лист Excel. Вам будет предложено сохранить рабочую книгу.

Источник

Excel Sheet in VB.net – How to Create an Excel File Using VB.net

Excel Sheet in VB.net – VB.net makes it possible for the COM object model of Microsoft Excel 2010 to work with your application.

To use this interoperability in your application, you need to add the namespace Microsoft.Office.Interop.Excel to your Windows Form Application.

Today I will teach you about How to Create an Excel File Using VB.net. Create an Excel File Using Visual Basic.Net provides support for interoperability between the COM object model of Microsoft Excel and your application.

Table of contents

We have learned how to use the Regular Expression in VB.net in the previous lesson. In this lesson we shall learn How To Write a Program for Excel Sheet in VB.net.

What is Visual Basic’s purpose?

The third-generation programming language was created to aid developers in the creation of Windows applications. It has a programming environment that allows programmers to write code in.exe or executable files.

They can also utilize it to create in-house front-end solutions for interacting with huge databases. Because the language allows for continuing changes, you can keep coding and revising your work as needed.

However, there are some limits to the Microsoft Visual Basic download. If you want to make applications that take a long time to process, this software isn’t for you.

That implies you won’t be able to use VB to create games or large apps because the system’s graphic interface requires a lot of memory and space.

Furthermore, the language is limited to Microsoft and does not support other operating systems.

What is Excel Sheet in VB.net?

In Excel documents, a Worksheet is a group of cells that are set up in rows and columns. It is the part of the computer you use to enter data.

Each worksheet has 1048576 rows and 16384 columns, making it a big table that you can use to organize information.

So let’s get started:

How to Create an Excel File Using VB.net

Steps in Creating an Excel Application from VB.net.

Time needed: 5 minutes.

Creating an Excel Application from VB.net

    Step 1: Create New Project

First is open the Visual Basic, Select File on the menu, then click New and create a new project.

Step 2: Name your Project

Then a New Project Dialog will appear. You can rename your project, depending on what you like to name it. After that click OK

Step 3: Design your Windows Form

Then design your form like this just like what I’ve shown you below
Add a Button from the toolbox.

Step 4: Add Reference

After that, Add a Reference to Microsoft Excel Object Library to your project.
To do this:
*Select add reference from the project menu.

Step 5: Locate Microsoft Excel Object Library

On the COM tab, Locate Microsoft Excel Object Library and then click select.

Step 6: Add Following Code

Double click the code window and add this following code to the top of Public Class Form1.

Imports Excel = Microsoft.Office.Interop.Excel
Step 7: Double click the Button and add this following code

Then, Go back to Design View and Double click the Button and add this following code.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim appXL As Excel.Application
Dim wbXl As Excel.Workbook
Dim shXL As Excel.Worksheet
Dim raXL As Excel.Range
appXL = CreateObject(“Excel.Application”)
appXL.Visible = True
wbXl = appXL.Workbooks.Add
shXL = wbXl.ActiveSheet
shXL.Cells(1, 1).Value = “FIRST NAME”
shXL.Cells(1, 2).Value = “LAST NAME”
shXL.Cells(1, 3).Value = “FULL NAME”
shXL.Cells(1, 4).Value = “SUBJECTS”
With shXL.Range(“A1”, “D1”)
.Font.Bold = True
.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
End With
Dim pupils(5, 2) As String
pupils(0, 0) = “Markfil”
pupils(0, 1) = “Baldomero”
pupils(1, 0) = “Juvy”
pupils(1, 1) = “Aral”
pupils(2, 0) = “Andrew”
pupils(2, 1) = “Braza”
pupils(3, 0) = “Carlie”
pupils(3, 1) = “Golez”
pupils(4, 0) = “Jesriel”
pupils(4, 1) = “Agita”
shXL.Range(“A2”, “B6”).Value = pupils
raXL = shXL.Range(“C2”, “C6”)
raXL.Formula = “=A2 & “” “” & B2″
With shXL
.Cells(2, 4).Value = “English”
.Cells(3, 4).Value = “Algebra”
.Cells(4, 4).Value = “Physics”
.Cells(5, 4).Value = “Trigonometry”
.Cells(6, 4).Value = “Theology”
End With
raXL = shXL.Range(“A1”, “D1”)
raXL.EntireColumn.AutoFit()
appXL.Visible = True
appXL.UserControl = True
raXL = Nothing
shXL = Nothing
wbXl = Nothing
appXL.Quit()
appXL = Nothing
Exit Sub
Err_Handler:
MsgBox(Err.Description, vbCritical, “Error: ” & Err.Number)
End Sub

Step 8: Click F5 to run the program.

Finally, Click F5 to run the program.

Program Output:

Download the Source Code:

Summary

This article shows how to make an Excel sheet and how to fill a range of cells with a number of different values. This article also shows how to get a range of cells as an array of cells.

Источник

Vb net создать файл excel

Answered by:

Question

VWD 2008 Express. Visual Basic.

Is it possible to build an Excel workbook from VB code behind an aspx page. What do I need to do? Can anyone provide a code sample? Thanks.

Answers

I needed to use the following to get the Excel 2003 library:

xlApp = New Excel.ApplicationClass (Which seems to create an Excel 2007 file)

xlApp = New Excel.Application (Which creates an Excel 2003 file)

So the whole thing is:

Not knowing your exact needs, this code sample from ASPNet101.com shows how to export from a Gridview to an Excel file

Thanks for the reply. What I need and want to do is to build an Excel file NOT from a GridView control, but from data I am generating programmatically. I need to be able to create the Excel file, and populate some of its cells with data I have programmatically. I know how to create a regular text file (>CSV) from my VB code behind, but I really need to create a true Excel file. Any other ideas? Thnaks.

I am trying to work with the code example to which you refer. It produces an Excel worksheet, but the first row is blank and then row 2 has my headings (field names top be used in a mail merge). Why would a blank row be placed before the actual header row? How can I get rid of it? Thanks for any additional help.

There are three approaches can export to excel file, approach 2 and 3 are helpful to you.

1.One is using GridView that is bound on DataSet from database. And export GridView to Excel File. http://forums.asp.net/t/1197704/2076903.aspx .
2.Another approach is more flexible: Write an Excel file directly via the data in DataSet. http://forums.asp.net/p/1222903/2189537.aspx .

3.As to export the data to existing excel file or write data into specific cell of excel file, you can use Excel Library: http://forums.asp.net/p/1235485/2244394.aspx .

In this approach, you can define more details about the cells. For example, define the style and format of cells in excel file that is unavailable with the other two approaches.

Thanks for the link. This deals with Visual Studio.NET. I am using Visual Web Developer 2008 Express. However, I went through the steps of adding the reference to the Microsoft Excel 11.0 Object Library (Website>Add Reference), then adding the following at the top of my class module:

But I get the error mesage:

Warning 1 Namespace or type specified in the Imports ‘Microsoft.Office.Interop.Excel’ doesn’t contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn’t use any aliases.

What other steps might I need to use the example at the link you gave in my VWD 2008 application?

Источник

VB.Net — Excel Sheet

VB.Net provides support for interoperability between the COM object model of Microsoft Excel 2010 and your application.

To avail this interoperability in your application, you need to import the namespace Microsoft.Office.Interop.Excel in your Windows Form Application.

Creating an Excel Application from VB.Net

Let’s start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio: File → New Project → Windows Forms Applications

Finally, select OK, Microsoft Visual Studio creates your project and displays following Form1.

Insert a Button control Button1 in the form.

Add a reference to Microsoft Excel Object Library to your project. To do this −

Select Add Reference from the Project Menu.

    On the COM tab, locate Microsoft Excel Object Library and then click Select.

    Double click the code window and populate the Click event of Button1, as shown below.

    When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −

    Clicking on the Button would display the following excel sheet. You will be asked to save the workbook.

    Источник

ГЛАВНАЯ

ТРЕНИНГИ

   Быстрый старт
   Расширенный Excel
   Мастер Формул
   Прогнозирование
   Визуализация
   Макросы на VBA

КНИГИ

   Готовые решения
   Мастер Формул
   Скульптор данных

ВИДЕОУРОКИ

ПРИЕМЫ

   Бизнес-анализ
   Выпадающие списки
   Даты и время
   Диаграммы
   Диапазоны
   Дубликаты
   Защита данных
   Интернет, email
   Книги, листы
   Макросы
   Сводные таблицы
   Текст
   Форматирование
   Функции
   Всякое
PLEX

   Коротко
   Подробно
   Версии
   Вопрос-Ответ
   Скачать
   Купить

ПРОЕКТЫ

ОНЛАЙН-КУРСЫ

ФОРУМ

   Excel
   Работа
   PLEX

© Николай Павлов, Planetaexcel, 2006-2022
info@planetaexcel.ru


Использование любых материалов сайта допускается строго с указанием прямой ссылки на источник, упоминанием названия сайта, имени автора и неизменности исходного текста и иллюстраций.

Техническая поддержка сайта

ООО «Планета Эксел»

ИНН 7735603520


ОГРН 1147746834949
        ИП Павлов Николай Владимирович
        ИНН 633015842586
        ОГРНИП 310633031600071 

OK this isn’t perfect but it should get you started. First of all you will want to add a reference to the version of Excel you are using. In my case it is 12.0 (2007) but this code should work with the last two or three version with a minor change or two. At the top of your page add this

Imports Microsoft.Office.Interop

Next add a function to create a datatable

Public Function CreateTable() As DataTable
    Dim cn As New SqlConnection(My.Settings.con)
    Dim cmd As New SqlCommand
    Using da As New SqlDataAdapter()
        Dim dt As New DataTable()
        cmd.CommandType = CommandType.StoredProcedure
        cmd.CommandText = "[dbo].[MyStoredProcedure]"
        cmd.CommandTimeout = 0
        cn.Open()
        cmd.Connection = cn
        da.SelectCommand = cmd
        da.Fill(dt)
        cn.Close()
        Return dt
    End Using
End Function

Next the code to take that DataTable and dump it into Excel.

Public Shared Sub PopulateSheet(ByVal dt As DataTable, ByVal File As String)
            Dim oXL As Excel.Application = CType(CreateObject("Excel.Application"), Excel.Application)
        Dim oWB As Excel.Workbook
        Dim oSheet As Excel.Worksheet
        Dim oRng As Excel.Range
        oXL.Visible = True

        oWB = oXL.Workbooks.Add
        oSheet = CType(oWB.ActiveSheet, Excel.Worksheet)

        Dim dc As DataColumn
        Dim dr As DataRow
        Dim colIndex As Integer = 0
        Dim rowIndex As Integer = 0
        For Each dc In dt.Columns
            colIndex = colIndex + 1
            oXL.Cells(1, colIndex) = dc.ColumnName
        Next
        For Each dr In dt.Rows
            rowIndex = rowIndex + 1
            colIndex = 0
            For Each dc In dt.Columns
                colIndex = colIndex + 1
                oXL.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
            Next
        Next

        oSheet.Cells.Select()
        oSheet.Columns.AutoFit()
        oSheet.Rows.AutoFit()

        oXL.Visible = True
        oXL.UserControl = True

        oWB.SaveAs(File)
        oRng = Nothing
        oXL.Quit()

        ExcelCleanUp(oXL, oWB, oSheet)
    End Sub

Now you can call it from a button or whatever event you choose with this

    Dim dt As New DataTable
    Try
        dt = CreateTable()
        PopulateSheet(dt, "c:testExcelFile.xlsx")
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        dt.Dispose()
    End Try

Now this is really basic but with a little work you can do cell formatting, page setup and just about anything that can be done inside Excel with the menus/options.

We should also finish this out by adding code to clean things up.

Private Shared Sub ExcelCleanUp( _
    ByVal oXL As Excel.Application, _
    ByVal oWB As Excel.Workbook, _
    ByVal oSheet As Excel.Worksheet)

    GC.Collect()
    GC.WaitForPendingFinalizers()

    Marshal.FinalReleaseComObject(oXL)
    Marshal.FinalReleaseComObject(oSheet)
    Marshal.FinalReleaseComObject(oWB)

    oSheet = Nothing
    oWB = Nothing
    oXL = Nothing

End Sub

VB.Net обеспечивает поддержку взаимодействия между объектной моделью COM Microsoft Excel 2010 и вашим приложением.

Чтобы использовать эту совместимость в вашем приложении, вам необходимо импортировать пространство имен Microsoft.Office.Interop.Excel в ваше приложение Windows Form.

Создание приложения Excel из VB.Net

Давайте начнем с создания приложения Window Forms, выполнив следующие шаги в Microsoft Visual Studio: Файл → Новый проект → Приложения Windows Forms.

Наконец, нажмите OK, Microsoft Visual Studio создаст ваш проект и отобразит следующую форму Form1 .

Вставьте элемент управления Button1 в форму.

Добавьте ссылку на библиотеку объектов Microsoft Excel в свой проект. Для этого –

  • Выберите Добавить ссылку в меню проекта.

Выберите Добавить ссылку в меню проекта.

Добавить ссылку

  • На вкладке COM найдите библиотеку объектов Microsoft Excel и нажмите «Выбрать».

На вкладке COM найдите библиотеку объектов Microsoft Excel и нажмите «Выбрать».

Вкладка COM

  • Нажмите ОК.

Нажмите ОК.

Дважды щелкните окно кода и заполните событие Click для Button1, как показано ниже.

'  Add the following code snippet on top of Form1.vb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      Dim appXL As Excel.Application
      Dim wbXl As Excel.Workbook
      Dim shXL As Excel.Worksheet
      Dim raXL As Excel.Range
      
      ' Start Excel and get Application object.
      appXL = CreateObject("Excel.Application")
      appXL.Visible = True
      
      ' Add a new workbook.
      wbXl = appXL.Workbooks.Add
      shXL = wbXl.ActiveSheet
      
      ' Add table headers going cell by cell.
      shXL.Cells(1, 1).Value = "First Name"
      shXL.Cells(1, 2).Value = "Last Name"
      shXL.Cells(1, 3).Value = "Full Name"
      shXL.Cells(1, 4).Value = "Specialization"
      
      ' Format A1:D1 as bold, vertical alignment = center.
      With shXL.Range("A1", "D1")
         .Font.Bold = True
         .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
      End With
      
      ' Create an array to set multiple values at once.
      Dim students(5, 2) As String
      students(0, 0) = "Zara"
      students(0, 1) = "Ali"
      students(1, 0) = "Nuha"
      students(1, 1) = "Ali"
      students(2, 0) = "Arilia"
      students(2, 1) = "RamKumar"
      students(3, 0) = "Rita"
      students(3, 1) = "Jones"
      students(4, 0) = "Umme"
      students(4, 1) = "Ayman"
      
      ' Fill A2:B6 with an array of values (First and Last Names).
      shXL.Range("A2", "B6").Value = students
      
      ' Fill C2:C6 with a relative formula (=A2 & " " & B2).
      raXL = shXL.Range("C2", "C6")
      raXL.Formula = "=A2 & "" "" & B2"
       
      ' Fill D2:D6 values.
      With shXL
         .Cells(2, 4).Value = "Biology"
         .Cells(3, 4).Value = "Mathmematics"
         .Cells(4, 4).Value = "Physics"
         .Cells(5, 4).Value = "Mathmematics"
         .Cells(6, 4).Value = "Arabic"
      End With
      
      ' AutoFit columns A:D.
      raXL = shXL.Range("A1", "D1")
      raXL.EntireColumn.AutoFit()
      
      ' Make sure Excel is visible and give the user control
      ' of Excel's lifetime.
      appXL.Visible = True
      appXL.UserControl = True
      
      ' Release object references.
      raXL = Nothing
      shXL = Nothing
      wbXl = Nothing
      appXL.Quit()
      appXL = Nothing
      Exit Sub
Err_Handler:
      MsgBox(Err.Description, vbCritical, "Error: " & Err.Number)
   End Sub
End Class

Когда приведенный выше код будет выполнен и запущен с использованием кнопки « Пуск» , доступной на панели инструментов Microsoft Visual Studio, появится следующее окно:

Пример VB.Net Excel

При нажатии на кнопку отобразится следующий лист Excel. Вам будет предложено сохранить рабочую книгу.

Содержание

  • 1 Calculate Expression
  • 2 Create a Spreadsheet
  • 3 Create function in Excel
  • 4 Import data
  • 5 Sort imported data

Calculate Expression

<source lang=»vbnet»>public class Test

  public Shared Sub Main
       Dim objExcel As Excel.Application
       objExcel = New Excel.Application
       Dim strMath As String
       strMath = "cos(3.673/4)/exp(-3.333)"
       If strMath <> "" Then
           Try
               Console.WriteLine(objExcel.Evaluate(strMath).ToString)
           Catch exc As Exception
               Console.WriteLine(exc.Message)
           End Try
       End If
       objExcel.Workbooks.Close()
       objExcel.Quit()
       objExcel = Nothing
  End Sub

End class</source>

Create a Spreadsheet

<source lang=»vbnet»>public class Test

  public Shared Sub Main
       Dim objExcel As Excel.Application
       objExcel = New Excel.Application
   
       Dim objSheet As New Excel.Worksheet
       Dim objRange As Excel.Range
       Dim intRow, intCol As Integer
       objExcel.Visible = True
       "Add a worksheet and then add some content to it.
       objSheet = objExcel.Workbooks.Add.Worksheets.Add
       With objSheet
           .Cells(2, 1).Value = "1st Quarter"
           .Cells(2, 2).Value = "2nd Quarter"
           .Cells(2, 3).Value = "3rd Quarter"
           .Cells(2, 4).Value = "4th Quarter"
           .Cells(2, 5).Value = "Year Total"
           .Cells(3, 1).Value = 123.45
           .Cells(3, 2).Value = 435.56
           .Cells(3, 3).Value = 376.25
           .Cells(3, 4).Value = 425.75
           .Range("A2:E2").Select()
           With objExcel.Selection.Font
               .Name = "Verdana"
               .FontStyle = "Bold"
               .Size = 12
           End With
       End With
       "Set the alignment.
       objSheet.Range("A2:E2").Select()
       objExcel.Selection.Columns.AutoFit()
       objSheet.Range("A2:E2").Select()
       With objExcel.Selection
           .HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
       End With
       "Format some numbers.
       objSheet.Range("A3:E3").Select()
       With objExcel.Selection.Font
           .Name = "Verdana"
           .FontStyle = "Regular"
           .Size = 11
       End With
       "Display summary information.
       objSheet.Cells(3, 5).Value = "=Sum(A3:D3)"
       objRange = objSheet.UsedRange
       For intCol = 1 To objRange.Columns.Count
           For intRow = 1 To objRange.Rows.Count
               Console.WriteLine(objRange.Cells(intRow, intCol).value)
           Next
       Next
       objExcel.Workbooks.Close()
       objExcel.Quit()
       objExcel = Nothing
  End Sub

End class</source>

Create function in Excel

<source lang=»vbnet»>public class Test

  public Shared Sub Main
       Dim objExcel As New Excel.Application
       objExcel.Visible = True
       objExcel.Workbooks.Add()
       objExcel.Range("A1").Select()
       objExcel.ActiveCell.FormulaR1C1 = "75"
       objExcel.Range("B1").Select()
       objExcel.ActiveCell.FormulaR1C1 = "125"
       objExcel.Range("C1").Select()
       objExcel.ActiveCell.FormulaR1C1 = "255"
       objExcel.Range("D1").Select()
       objExcel.ActiveCell.FormulaR1C1 = "295"
       objExcel.Range("A1:D1").Select()
       objExcel.Range("E1").Activate()
       objExcel.ActiveCell.FormulaR1C1 = "=SUM(RC[-4]:RC[-1])"
       objExcel.Range("A1:E1").Select()
       objExcel.Selection.Font.Bold = True
       objExcel = Nothing
  End Sub

End Class</source>

Import data

<source lang=»vbnet»>public class Test

  public Shared Sub Main
       Dim objExcel As Excel.Application
       objExcel = New Excel.Application
   
       Dim objSheet As New Excel.Worksheet
       Dim objData As Excel.Range
       Dim intCol, intRow As Integer
       objExcel.Visible = True
       TextBox1.Clear()
       objSheet = objExcel.Workbooks.Open("C:TempTest.xls").Worksheets.Item(1)
       objExcel.Range("A2:E3").Select()
       objData = objExcel.Selection
       For intCol = 1 To 5
           For intRow = 1 To 2
               Console.WriteLine(objData(intRow, intCol).Value)
           Next
       Next
       objExcel.Workbooks.Close()
       objExcel.Quit()
       objExcel = Nothing
  End Sub

End class</source>

Sort imported data

<source lang=»vbnet»>public class Test

  public Shared Sub Main
       Dim objExcel As Excel.Application
       objExcel = New Excel.Application
   
       Dim objSheet As New Excel.Worksheet
       Dim objData As Excel.Range
       Dim intCol, intRow As Integer
       Call OpenExcel()
       objExcel.Visible = True
       objSheet = objExcel.Workbooks.Open("C:TempTest.xls").Worksheets.Item(1)
       objExcel.Range("A2:E3").Select()
       objData = objExcel.Selection
       objData.Sort(Key1:=objData.Range("A2"), Order1:=Excel.XlSortOrder.xlAscending)
       For intCol = 1 To 5
           For intRow = 1 To 2
               Console.WriteLine(objData(intRow, intCol).value)
           Next
       Next
       objExcel.Workbooks.Close()
       objExcel.Quit()
       objExcel = Nothing
  End Sub

End class</source>

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

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

  • Как создать файл excel без excel
  • Как создать файл excel python
  • Как создать файл doc в microsoft word
  • Как создать учетную запись для word
  • Как создать учетную запись в microsoft word

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

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