Запись от po4emy4ka размещена 02.02.2014 в 01:05
Обновил(-а) po4emy4ka 02.02.2014 в 01:13
(Добавил архив с исходниками)
Шаг 1
Шаг 2 (можно в поиске набрать excel, чтобы было удобней)
Добавить в наш проект подключение типов и переменные.
Шаг 3
Для того, что бы при закрытии нашей программы в памяти не оставалось приложение Excel, мы его будем закрывать перед закрытием самой формы.
Шаг 4
Итак, откроем наш первый файл test_vb.xls в нашем приложении:
VB.NET | ||
|
Изначально приложение Excel будет находится в невидимом состоянии (скрытый процесс) и если нам ничего никому показывать не нужно, то это даже очень удобно. А вот если нам нужно видеть, что же происходит то лучше отобразить приложение Excel. Для этого добавим на форму еще одну кнопку и напишем для нее обработчик.
VB.NET | ||
|
ExApp.Visible = False — Скрытый режим
ExApp.Visible = True — Видимый режим
Excel_VBNET.rar
Всего комментариев
In this tutorial, I will teach you how to read an excel file in Visual basic.net (VB.Net).
This tutorial can be integrated to your personalized vb.net project.
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.
So let’s get started:
Step How to Read an Excel file in Visual Basic.Net
- Step 1: First is open the Visual Basic, Select File on the menu, then click New and create a new project.
- Step 2: 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 form like this just like what I’ve shown you below.
Add a 2 Textbox and a Button
- Step 4: After designing your form. Add a reference to Microsoft Excel 12.0 Object Library
In your project menu click on Project– Add Reference – go to COM tab
Add Microsoft Excel 12.0 Object Library
- Step 5: Then, go to the code page and add the following declarations:
Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Dim APP As New Excel.Application Dim worksheet As Excel.Worksheet Dim workbook As Excel.Workbook
- Step 6: Add this following code to Form_Load Event
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load workbook = APP.Workbooks.Open("C:UsersCliveDocumentsVisual Studio 2008clive projectswriteandreadwriteandreadbinDebugsales.xlsx") worksheet = workbook.Worksheets("sheet1") End Sub
Step 7: To get the value from Excel cell to TextBox. Add this following code to the Button Click Event.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles Button1.Click TextBox1.Text = worksheet.Cells(1, 1).Value TextBox2.Text = worksheet.Cells(1, 2).Value End Sub
Step 8: Then finally, add this code to save the Excel file and closes it.
Private Sub Form1_FormClosed(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.FormClosedEventArgs) _ Handles MyBase.FormClosed workbook.Save() workbook.Close() App.Quit() End Sub
- Step 9: Click F5 to run the program.
Inquiries
If you have any questions or suggestions about How to Read an Excel file using Visual Basic.Net please contact me through our contact page or simply leave a comment below.
Download the Code Below
Download How to Read an Excel file using Visual Basic.Net Source code here.
Readers might read also:
- How to Export DataGridView Data to Excel using VB.Net
- How to Create an Excel File Using Visual Basic.Net
- Basic Calculator Using Visual Basic.Net
If you want to get started with a little bit of advance topic in VB.Net you may start your lesson here on how to connect access database to vb.net. Watch the video here below.
- Remove From My Forums
-
Question
-
I’m trying to open an Excel workbook from VB.Net. I’m using VS 2005. The procedure that is trying to open the file looks like this:
Public Sub DisplayExcelFile() ' --------------------------------------------------------------------------------------- ' Procedure: DisplayExcelFile() ' DateTime : 5/20/13 ' Author: snyderg() ' Purpose : This routine displays the Excel spreadsheet at location strPath. ' To call: Session("strExcelFilePath") = ExcelFilePath ' Call DisplayExcelFile("Path") ' --------------------------------------------------------------------------------------- Dim xlsApp As Excel.Application = Nothing Dim xlsWorkBooks As Excel.Workbooks = Nothing Dim xlsWB As Excel.Workbook = Nothing Try xlsApp = New Excel.Application xlsApp.Visible = True xlsWorkBooks = xlsApp.Workbooks xlsWB = xlsWorkbooks.Open(Session("strExcelFilePath")) Catch ex As Exception Finally xlsWB.Close() xlsWB = Nothing xlsApp.Quit() xlsApp = Nothing End Try End Sub
I begin the class with the statements:
Imports Excel = Microsoft.Office.Interop.Exel
Imports Microsoft.Office
When I call the procedure, I get «Incorrect Syntax Near ‘Microsoft’.» I have commented the entire procedure except for the first Dim statement:
«Dim xlsApp = New.Excel.Application»
but I still get the error. The project builds without error.
Can anyone suggest why I get this syntax error and how to correct it?
Retred Air Force
Answers
-
First place the import statements at the top of the form or code module you are working in
Imports Excel = Microsoft.Office.Interop.Excel Imports Microsoft.Office
Code to open Excel (read the MessageBox within the code)
Public Sub OpenExcelDemo(ByVal FileName As String, ByVal SheetName As String) If IO.File.Exists(FileName) Then Dim Proceed As Boolean = False Dim xlApp As Excel.Application = Nothing Dim xlWorkBooks As Excel.Workbooks = Nothing Dim xlWorkBook As Excel.Workbook = Nothing Dim xlWorkSheet As Excel.Worksheet = Nothing Dim xlWorkSheets As Excel.Sheets = Nothing Dim xlCells As Excel.Range = Nothing xlApp = New Excel.Application xlApp.DisplayAlerts = False xlWorkBooks = xlApp.Workbooks xlWorkBook = xlWorkBooks.Open(FileName) xlApp.Visible = True xlWorkSheets = xlWorkBook.Sheets For x As Integer = 1 To xlWorkSheets.Count xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet) If xlWorkSheet.Name = SheetName Then Console.WriteLine(SheetName) Proceed = True Exit For End If Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet) xlWorkSheet = Nothing Next If Proceed Then xlWorkSheet.Activate() MessageBox.Show("File is open, if you close Excel just opened outside of this program we will crash-n-burn.") Else MessageBox.Show(SheetName & " not found.") End If xlWorkBook.Close() xlApp.UserControl = True xlApp.Quit() ReleaseComObject(xlCells) ReleaseComObject(xlWorkSheets) ReleaseComObject(xlWorkSheet) ReleaseComObject(xlWorkBook) ReleaseComObject(xlWorkBooks) ReleaseComObject(xlApp) Else MessageBox.Show("'" & FileName & "' not located. Try one of the write examples first.") End If End Sub Public Sub ReleaseComObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing End Try End Sub
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.
-
Proposed as answer by
Wednesday, May 22, 2013 6:12 AM
-
Marked as answer by
Youen Zen
Wednesday, June 5, 2013 6:18 AM
-
Proposed as answer by
-
-
Edited by
Paul P Clement IV
Tuesday, May 21, 2013 4:59 PM -
Proposed as answer by
Ed Price — MSFTMicrosoft employee
Wednesday, May 22, 2013 6:12 AM -
Marked as answer by
Youen Zen
Wednesday, June 5, 2013 6:18 AM
-
Edited by
- Download source code — 10.6 KB
Introduction
This articles helps user to Insert, Update, Delete, and Select data in Excel files using the OLEDBDataProvider
in VB.NET.
Here is the connection string to connect with Excel using OleDBDataProvider
:
Private Const connstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:Test.xls;Extended Properties=""Excel 8.0;HDR=YES;"""
Here is the code on the button click event to select and insert data in an Excel file:
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim pram As OleDbParameter Dim dr As DataRow Dim olecon As OleDbConnection Dim olecomm As OleDbCommand Dim olecomm1 As OleDbCommand Dim oleadpt As OleDbDataAdapter Dim ds As DataSet Try olecon = New OleDbConnection olecon.ConnectionString = connstring olecomm = New OleDbCommand olecomm.CommandText = _ "Select FirstName, LastName, Age, Phone from [Sheet1$]" olecomm.Connection = olecon olecomm1 = New OleDbCommand olecomm1.CommandText = "Insert into [Sheet1$] " & _ "(FirstName, LastName, Age, Phone) values " & _ "(@FName, @LName, @Age, @Phone)" olecomm1.Connection = olecon pram = olecomm1.Parameters.Add("@FName", OleDbType.VarChar) pram.SourceColumn = "FirstName" pram = olecomm1.Parameters.Add("@LName", OleDbType.VarChar) pram.SourceColumn = "LastName" pram = olecomm1.Parameters.Add("@Age", OleDbType.VarChar) pram.SourceColumn = "Age" pram = olecomm1.Parameters.Add("@Phone", OleDbType.VarChar) pram.SourceColumn = "Phone" oleadpt = New OleDbDataAdapter(olecomm) ds = New DataSet olecon.Open() oleadpt.Fill(ds, "Sheet1") If IsNothing(ds) = False Then dr = ds.Tables(0).NewRow dr("FirstName") = "Raman" dr("LastName") = "Tayal" dr("Age") = 24 dr("Phone") = 98989898 ds.Tables(0).Rows.Add(dr) oleadpt = New OleDbDataAdapter oleadpt.InsertCommand = olecomm1 Dim i As Integer = oleadpt.Update(ds, "Sheet1") MessageBox.Show(i & " row affected") End If Catch ex As Exception MessageBox.Show(ex.Message) Finally olecon.Close() olecon = Nothing olecomm = Nothing oleadpt = Nothing ds = Nothing dr = Nothing pram = Nothing End Try End Sub
This member has not yet provided a Biography. Assume it’s interesting and varied, and probably something to do with programming.
I followed this site to get me started on my program, here
When I add the reference and declare my variables:
Imports Excel = Microsoft.Office.Interop.Excel
Class XCel
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
End Class
I get an ambiguity error, » ‘Application’ is ambiguous in the namespace ‘Microsoft.Office.Interop.Excel’ «
I’ve read a few pages saying to remove the reference then re-add it and updating the PIAs but none have helped.
Is there a simpler way to open an Excel? Something I’m missing in my code/project to get it to work?
asked Aug 27, 2012 at 17:30
Is there a simpler way to open an Excel?
The EPPlus open source project makes it much easier to work with Excel files than using Office Interop:
EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx).
http://epplus.codeplex.com/
I get an ambiguity error, » ‘Application’ is ambiguous in the namespace ‘Microsoft.Office.Interop.Excel’ «
I ran into the same error that you are getting now when I had PIA’s for more than one Office version installed on the same machine. I ended up resolving it by only installing the newest version of Excel on my development machine (because after all, I wanted to have the newest version of Office for general work) and creating a Virtual Machine that had the oldest version of Office that I needed to support that I used as a build machine to do the final release build and create the setup program for customers.
answered Aug 27, 2012 at 17:33
Eric J.Eric J.
147k63 gold badges339 silver badges551 bronze badges
4