Results 1 to 21 of 21

Thread: Read Excel Sheet

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Nov 2003
    Location
    Iowa
    Posts
    96

    Read Excel Sheet

    I just want to read an excel sheet, and change the sheet into a 2d array....I want it with an openfiledialog, but whatever i try just doesnt seem to work! Any guidance would be helpful! Please don't assume i know anything, assume i know nothing!! Thanks in advance for any help!
    It is like wiping your ass with silk, I love it!

  2. #2

    Thread Starter
    Lively Member
    Join Date
    Nov 2003
    Location
    Iowa
    Posts
    96
    ANY DIRECTION or SUGGESTION will help!! Please i'm desperate...!!
    It is like wiping your ass with silk, I love it!

  3. #3
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    Not too difficult, just need to know where to look.

    Try this:
    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.         Dim dtSchema As DataTable
    3.         Dim drSchema As DataRow
    4.         Dim strForTextBox As String
    5.         Dim fDlg As New OpenFileDialog
    6.         fDlg.Filter = "Excel Spreadsheets (*.xls)|*.xls"
    7.         fDlg.ShowDialog()
    8.         Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
    9.                                               "Data Source=" & fDlg.FileName & _
    10.                                               ";Extended Properties=Excel 8.0;")
    11.  
    12.         cn.Open()
    13.         dtSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
    14.  
    15.         DataGrid1.DataSource = dtSchema
    16.         'DataGrid1.SetDataBinding(dtSchema, "")
    17.         For Each drSchema In dtSchema.Rows
    18.             strForTextBox = strForTextBox & "Table name = " & drSchema("TABLE_NAME") & vbCrLf
    19.         Next
    20.  
    21.         TextBox1.Text = strForTextBox
    22.  
    23.         cn.Close()
    24.         cn.Dispose()
    25.     End Sub
    Whadayamean it doesn't work....
    It works fine on my machine!

  4. #4
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687
    Wow... does that really work? If so I jsut might have to *cough* borrow that for an app I'm working on.... certanly would make things easier since I wouldn't need to use the Excel model (thus making Office install manditory).

    TG
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  5. #5
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    Yeah, it works great, I have done a lot of work with excel spreadsheets in some side projects I have worked on. Hold on a sec because this just returns the schema, I'm working on code that also selects an individual sheet in a file and uses that as a datasource.
    Whadayamean it doesn't work....
    It works fine on my machine!

  6. #6
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    Updated code for opening a specific sheet in your .xls:
    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.         Dim dtSchema As DataTable
    3.         Dim drSchema As DataRow
    4.         Dim strForTextBox As String
    5.         Dim strTableName As String
    6.         Dim strSelect As String = "SELECT * FROM [{0}]"
    7.         Dim da As New OleDbDataAdapter
    8.         Dim ds As New DataTable
    9.         Dim fDlg As New OpenFileDialog
    10.         fDlg.Filter = "Excel Spreadsheets (*.xls)|*.xls"
    11.         fDlg.ShowDialog()
    12.         If fDlg.FileName.Length > 0 Then
    13.             Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
    14.                                                   "Data Source=" & fDlg.FileName & _
    15.                                                   ";Extended Properties=Excel 8.0;")
    16.  
    17.             cn.Open()
    18.             dtSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
    19.  
    20.             'DataGrid1.SetDataBinding(dtSchema, "")
    21.             drSchema = dtSchema.Rows(0)
    22.             strTableName = drSchema("TABLE_NAME")
    23.             Dim cmd As New OleDbCommand(String.Format(strSelect, strTableName))
    24.             cmd.Connection = cn
    25.             da.SelectCommand = cmd
    26.             da.Fill(ds)
    27.             'For Each drSchema In dtSchema.Rows
    28.             '    strForTextBox = strForTextBox & "Table name = " & drSchema("TABLE_NAME") & vbCrLf
    29.             'Next
    30.             DataGrid1.DataSource = ds
    31.  
    32.             'TextBox1.Text = strForTextBox
    33.  
    34.             cn.Close()
    35.             cn.Dispose()
    36.         End If
    37.     End Sub
    Whadayamean it doesn't work....
    It works fine on my machine!

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Nov 2003
    Location
    Iowa
    Posts
    96
    wow thanks a million man!! I'll go try it out!! however i don't feel comfortable using code that I don't understand, and I don't understand most of this code! I understand if you don't want to, but if you would be willing to kinda explain what is happening i would be MORE than grateful!! Also say what each line does, as i may want to change it to fit my own needs, and I can't do that if I don't know why it works, or what each line does!

    But thanks a million!!
    It is like wiping your ass with silk, I love it!

  8. #8

    Thread Starter
    Lively Member
    Join Date
    Nov 2003
    Location
    Iowa
    Posts
    96
    I get a build error, and a runtime error error...

    An unhandled exception of type 'System.InvalidCastException' occurred in Excel.exe

    Additional information: Specified cast is not valid.

    I get that error with this line

    Code:
     dtSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
    My build error comes here
    Code:
            Dim ds As New DataTable
    "New cannot be used on an interface."


    Any guidance again is helpful...:-( I really wish i understood this code, and btw, i had to add Imports System.data.oledb to make it work, things like that are nice to know b4 i see bunches of blue lines...
    It is like wiping your ass with silk, I love it!

  9. #9
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    Yep, sorry, I was in a hurry and just cut this code out of a project I am working on... well, I did add the file dialog code before I sent it.

    I'll comment it now and send it out again with explanations on what is going on there.
    Whadayamean it doesn't work....
    It works fine on my machine!

  10. #10
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    Here is the code with comments. I tested it again and it works fine here. If you are having a problem getting it to work, let me know which line it is breaking on and perhaps I can debug the problem.
    VB Code:
    1. 'Imports Statements
    2. Imports System
    3. Imports System.Data
    4. Imports System.Data.OleDb
    5.  
    6.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    7.         ' The declaration lines should be self explanatory
    8.         Dim daExcelData As New OleDbDataAdapter
    9.         Dim dtFirstTable As New DataTable
    10.         Dim drSchema As DataRow
    11.         Dim dtSchema As DataTable
    12.         Dim strForTextBox As String
    13.         Dim strTableName As String
    14.         Dim strSelect As String = "SELECT * FROM [{0}]"
    15.         Dim fDlg As New OpenFileDialog
    16.  
    17.         ' Clear the current contents of the datagrid
    18.         DataGrid1.DataSource = Nothing
    19.         ' Set the filter for the file dialog to show only spreadsheet files,
    20.         ' could be modified to include csv files also, but I don't need it.
    21.         fDlg.Filter = "Excel Spreadsheets (*.xls)|*.xls"
    22.         ' Show the file open dialog
    23.         fDlg.ShowDialog()
    24.         ' Make sure the user didn't click cancel...
    25.         If fDlg.FileName.Length > 0 Then
    26.             ' Declare the connection string, every section of this line is critical or the spreadsheet won't open
    27.             Dim cnExcelData As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
    28.                                                    "Data Source=" & fDlg.FileName & _
    29.                                                    ";Extended Properties=Excel 8.0;")
    30.             ' I hope this is self explanatory
    31.             cnExcelData.Open()
    32.             ' Read the database schema into a DataTable
    33.             dtSchema = cnExcelData.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
    34.             ' Get the first row in the table which will equate to the first sheet in the workbook
    35.             drSchema = dtSchema.Rows(0)
    36.             ' Get the name of the first sheet
    37.             strTableName = drSchema("TABLE_NAME")
    38.             ' create a command object to select the data from the first sheet in the workbook
    39.             Dim cmd As New OleDbCommand(String.Format(strSelect, strTableName))
    40.             ' I hope the following lines are self explanatory
    41.             cmd.Connection = cnExcelData
    42.             daExcelData.SelectCommand = cmd
    43.             daExcelData.Fill(dtFirstTable)
    44.             DataGrid1.DataSource = dtFirstTable
    45.             cnExcelData.Close()
    46.             cnExcelData.Dispose()
    47.         End If
    48.     End Sub

    The above code has served me well for the past few years, I have a client that insists on using spreadsheets for storage containers for certain data types because he knows how to manipulate the data in the sheets. I attempted to explain that he could just pull data from the database and insert it into the sheet when he needed, but alas....

    I hope this serves you as well as it has me
    Whadayamean it doesn't work....
    It works fine on my machine!

  11. #11

    Thread Starter
    Lively Member
    Join Date
    Nov 2003
    Location
    Iowa
    Posts
    96
    'New' cannot be used on an interface.

    I still get this error with this line of code...
    Code:
    Dim dtFirstTable As New DataTable
    I am also getting the -- An unhandled exception of type 'System.InvalidCastException' occurred in Excel.exe

    Additional information: Specified cast is not valid.

    from
    Code:
    dtSchema = cnExcelData.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})

    I changed the first error to DataSet, and it didnt give me any build errors..I think i may be missing something key, and i'll be like oh duh, but i just dont see it

    Thanks for documentation


    Also if you wouldn't mind telling me if i need anythign else on my form besides the datagrid, and the OpenFileDialog(not actually on form)

    Thanks for your help so far!!


    I feel like a leeching n00b...
    Last edited by thurst0n; Jul 13th, 2004 at 01:59 PM.
    It is like wiping your ass with silk, I love it!

  12. #12
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    'New' cannot be used on an interface.

    I still get this error with this line of code...
    Code:
    Dim dtFirstTable As New DataTable
    I don't receive this error with this code and it is directly from a working project I use. What version of VB.NET are you using?
    Whadayamean it doesn't work....
    It works fine on my machine!

  13. #13
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    Here is an example project that I put that code and and tested, as my tagline says, it works on my machine
    Attached Files Attached Files
    Whadayamean it doesn't work....
    It works fine on my machine!

  14. #14

    Thread Starter
    Lively Member
    Join Date
    Nov 2003
    Location
    Iowa
    Posts
    96
    Well yours works! thanks, i wonder why mine doesnt...i did it exactly wht you siad, i coppied and pasted...I sitll dont' understand what's going on though...i wish i did, i dont really feel comfortable using it...

    you've done quite enough so far but theres 1 more step, how do i USE this information, how do i get it when i need it...just an example of the assignment of one of the values would be great

    Thanks again!!
    It is like wiping your ass with silk, I love it!

  15. #15
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    What parts don't you understand, are you not familiar with ADO.NET, or is it SQL in general. This code couldn't be simpler. It simply establishes a connection to an Excel spreadsheet using the Jet OLEDB driver and then reads the schema from the workbook. For each sheet that is contained in the workbook, you can treat it as a database IF, it is formatted in a way that can be interpreted as an actual database. If you have five levels of headers, eg. World, Country, State, Locality, Address, it wouldn't know how to parse the data, you could end up with almost anything.
    you've done quite enough so far but theres 1 more step, how do i USE this information, how do i get it when i need it...just an example of the assignment of one of the values would be great
    What do you mean by this? Are you asking what you can do with the data in the table? If so, you would treat it as any other datasource, you can read it, update it, delete records, populate controls on a form, the possibilities are as endless as your imagination, what is it that you want to do with it?
    Whadayamean it doesn't work....
    It works fine on my machine!

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Nov 2003
    Location
    Iowa
    Posts
    96
    no no, i need to inturpret the data..This data will be from a questionaire so for example

    If Question1=2 then
    DO THIS
    End if

    etc etc, of course it will be much much larger
    lets say the answer for quetsion 2 is in the slot B1, how would i assign the value of B1 to the string Question1?? or how would i get the single data entry of B1..etc etc. i still feel like i'm not explaining myself verywell


    and as to the other thing, I'm not familiar with ADO or SQL i think i get the code, just not as comfortable with it
    It is like wiping your ass with silk, I love it!

  17. #17
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    It would be helpful if I could see an example of the data you have to read
    Whadayamean it doesn't work....
    It works fine on my machine!

  18. #18

    Thread Starter
    Lively Member
    Join Date
    Nov 2003
    Location
    Iowa
    Posts
    96
    sure thing i see your online right now i have both YAhoo and AIM, and MSN can you get on any of those? I knwo i can do all the petty stuff, but i don't know how to get hte program to know what is in a certain spot...

    Here is a sampletest, It's a "survey" filled out by 3 people, and they answered 4 questions...So how do i know what Person 1, answered to question 2?
    Attached Files Attached Files
    It is like wiping your ass with silk, I love it!

  19. #19

    Thread Starter
    Lively Member
    Join Date
    Nov 2003
    Location
    Iowa
    Posts
    96
    or can you put it into an array, i can work with that...but this datagrid is all new to me perhaps if you could point me into the direction of a simple tutorial, nothing deep, just the outskirts
    It is like wiping your ass with silk, I love it!

  20. #20
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    Since you are reading the data into a table, you don't really need the grid, I was just using that to show that you had in fact opened your data and had it in memory. You can think of a table as a two dimentional array with a "LOT" of extras, but baiscally it has columns and rows of data.
    Whadayamean it doesn't work....
    It works fine on my machine!

  21. #21
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    Here is an updated version that does not use the grid but uses the values in the table one at a time.
    Attached Files Attached Files
    Whadayamean it doesn't work....
    It works fine on my machine!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width