Click here to Skip to main content
Licence 
First Posted 23 Jul 2003
Views 189,242
Bookmarked 61 times

Automated Data Extraction to Excel in Visual Basic .NET

By | 23 Jul 2003 | Article
Based on user input, program pulls data from a database and extracts it to Microsoft Excel.

Purpose & background

About 2 months prior to writing this article, a need was brought to me to extract data in some way, but without me having to do it every month. Through trial and error, this is the best way that I've found so far. The application allows the user to input a beginning and end date, and then pull data based on that criteria. The data can be placed into either a DataGrid control, or an Excel spreadsheet. The DataGrid population is pretty straight forward, but the Excel extraction required some tinkering.

The code (or at least parts of it)

These are snippets of the ExtractData procedure, full code can be found in the source project/code.

First, you'll want to be sure to add references for both Excel (v. 9 for 2000, v. 10 for XP) and Office (same). Otherwise, this whole thing just won't work, and then I look like a giant tool, and nobody wins like that.

You'll want to make a new instance of the Excel application, then the workbook, then the actual worksheet you'll be working with. I've set the application to invisible for the time being. If someone begins to play around with the spreadsheet while it's being populated, the population of it will end and an error will be returned, and that would suck.

Private Sub ExtractData()
  If (beginDate.Value <= endDate.Value) Then
    Dim excelApp As New Excel.Application
    Dim excelBook As Excel.Workbook = excelApp.Workbooks.Add
    Dim excelWorksheet As Excel.Worksheet = _
        CType(excelBook.Worksheets(1), Excel.Worksheet)
    excelApp.Visible = False

We then need to create a disconnected table to populate the spreadsheet from. You know the drill:

With excelWorksheet
   Dim ds As New DataSet("DataSetName")
   Dim dr As DataRow
   Dim myConnection As New OleDb.OleDbConnection _
        ("Provider=Microsoft.Jet.OLEDB.4.0;Data " + _ 
        "Source=//server/folder/file.mdb;Persist Security Info=False")
   Dim myAdapter As New OleDb.OleDbDataAdapter
   Dim myCommand As New OleDb.OleDbCommand _
        (("SELECT LastName, FirstName, Details, " + _ 
        "DateWorkComplete FROM CompletedAll WHERE" + _ 
        " DateWorkComplete Between #" + _
        beginDate.Value.ToShortDateString() + "# And #" + _
        endDate.Value.ToShortDateString() + _ 
        "# ORDER BY Division, DateWorkComplete"), _
        myConnection)

Also, you'll want to format the cells in some way so that most everything's readable. You can adjust the setting, the value/font/width for the column headings with a simple Excel.Worksheet.Range("CellNumber").WhateverYouNeedToFormat.

  .Range("A1").Value = "Last Name"
  .Range("A1").Font.Bold = True
  .Range("A1").ColumnWidth = 15
  .Range("B1").Value = "First Name"
  .Range("B1").Font.Bold = True
  .Range("B1").ColumnWidth = 15

We then want to go through the data in the DataSet and place the values into the spreadsheet. That's done with a simple For Each statement. The name after the value call is simply the name of the field within the table.

For Each dr In ds.Tables(0).Rows
  .Range("A" & i.ToString).Value = dr("LastName")
  .Range("B" & i.ToString).Value = dr("FirstName")
  .Range("C" & i.ToString).Value = dr("DateWorkComplete")
  .Range("D" & i.ToString).Value = dr("DetailsOfProblem")
  i += 1
Next

We then finally need to make Excel visible.

excelApp.Visible = True

Again, the full code is in the source project/code above. If there any questions, contact me.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Kenneth Childs

Web Developer

United States United States

Member

Ken is a 28 year old web/database/application design geek at Duke University Medical Center's Department of Anesthesiology. He graduated from the prestegious North Carolina Wesleyan College in 2001 with a double degree in Computer Information Systems and Business Administration.
 
In his free time, he enjoys hiking, lacrosse, baseball, bowling, pool, candlelight dinners, long walks along a moonlit beach, and talking in the third person. You can e-mail him at child014@mc.duke.edu or IM him on AIM as KenAtDUMC or KenAtNCWC

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionHi Pinmembersrid80:17 16 Oct '11  
GeneralAlternative PinmemberCikaPero22:42 19 Apr '11  
Generalerrors Pinmemberlandra23:24 17 Jan '08  
GeneralHELP Pinmemberjarell3111:18 20 Jun '07  
Generalchange font color Pinmembervivek_pon18:16 28 Mar '06  
GeneralRe: change font color Pinmemberurssamba21:39 23 May '06  
Generalnot openning the Excel window Pinmembertinybunny_84:11 30 Jan '06  
GeneralADD REFRECE OF EXCEL Pinmembervivek_pon23:09 15 Jan '06  
Generalwhere is file.mdb PinmemberCihangir20027:13 15 Jan '05  
GeneralPrevent improper conversion PinmemberChuck77711:24 5 Oct '04  
GeneralDynamic Excel Creation Based on Results from SQL Pinmemberanthonylalba5:46 2 Jun '04  
GeneralSome options PinmemberMoustafa Ali1:43 1 Jun '04  
GeneralRe: Some options Pinmemberanthonylalba5:55 2 Jun '04  
GeneralRe: Some options PinmemberAlesKlemenc19:21 23 Mar '05  
GeneralLink to a different tutorial Pinmemberscorpion530613:16 27 May '04  
Questionhow to add and retreive data from excel by c#.Net 2002 PinsussGeorgeWagdy10:10 19 Apr '04  
Generalerror runing example Pinmemberscumpa0:50 14 Apr '04  
GeneralRe: error runing example Pinmemberscumpa1:07 16 Apr '04  
GeneralRe: error runing example Pinmembertuyennv21:40 11 Oct '04  
GeneralStopping the Excel process PinsussCindie4:20 30 Mar '04  
GeneralRe: Stopping the Excel process PinmemberMort Barsky11:19 27 Apr '04  
GeneralRe: Stopping the Excel process Pinmemberocbka2118:38 18 May '04  
GeneralONLINE DOCUMENTATION PinmemberKenneth Childs2:28 29 Oct '03  
Generalcannot launch source code Pinmemberrapace7:59 18 Sep '03  
Generalprob viewing the source code Pinmemberbiott20:40 31 Jul '03  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 24 Jul 2003
Article Copyright 2003 by Kenneth Childs
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid