View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Paul Reynolds[_2_] Paul Reynolds[_2_] is offline
external usenet poster
 
Posts: 8
Default Opening Excel in my program

This is a simple example in VB.NET. It assumes that the column names are in
the first row and that the last row on a worksheet can be determined by
looking for an empty cell in the first column. You need to set up a
reference to the Excel object library for this to work.

This function takes the workbook filename (full path) as an argument and
returns a DataSet with one DataTable for each worksheet.

Private Function fImportData(ByVal sWorkbookName As String) As DataSet
Dim xlApp As Excel.Application, xwbImport As Excel.Workbook,
xwsImport As Excel.Worksheet
Dim dtWorksheet As DataTable
Dim drCurrRow As DataRow
Dim nColumn As Integer, nRow As Integer

xlApp = New Excel.Application()
xwbImport = xlApp.Workbooks.Open(sWorkbookName)
fImportData = New DataSet()
For Each xwsImport In xwbImport.Worksheets
If xwsImport.Cells(1, 1).Value < "" Then
dtWorksheet = fImportData.Tables.Add(xwsImport.Name)
nColumn = 1
While xwsImport.Cells(1, nColumn).Value < ""
dtWorksheet.Columns.Add(xwsImport.Cells(1,
nColumn).Value)
nColumn = nColumn + 1
End While
nRow = 2
While xwsImport.Cells(nRow, 1).Value < ""
nColumn = 1
drCurrRow = dtWorksheet.NewRow
While xwsImport.Cells(1, nColumn).value < ""
drCurrRow(nColumn - 1) = xwsImport.Cells(nRow,
nColumn).Value
nColumn = nColumn + 1
End While
dtWorksheet.Rows.Add(drCurrRow)
nRow = nRow + 1
End While
End If
Next xwsImport
End Function

Hope this helps,
Paul

"Edgar" wrote in message
...
I had best explain what I'm doing first. I need to write
a method in C# that will open an excel file and read the
contents into a DataSet, which will then be placed into a
database. I would like to write it such that my method
signature is this: public void FromExcel(string fileName)
{...body...}. While I am writing this method in C# I
will welcome VB.NET examples. Thank you.