ライセンスが高いんじゃよー!(本音)

Excelをインストールしていない環境で、VB.NETを使ってExcelファイルの内容を読み込みたい。
てことがあったのですよ。
無理だろと思っておったのですが、いやあできるもんなんですね。
取り込んだ内容をテキストファイルに吐き出します。
例によって、後処理とか手抜きです。


Imports System.Data.OleDb

Public Class Form1
Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim txt As String
Dim strFileName As String = "取込ファイル.xls"
txt = DataSet(strFileName)

Dim fso As Object
fso = CreateObject("Scripting.FileSystemObject")
With fso.OpenTextfile("output.txt", 8, True)
.WriteLine(strFileName)
.WriteLine(txt)
.Close()
End With
fso = Nothing
Call MsgBox("おしまい!")
End Sub

Private Function DataSet(path As String) As String
Dim conString As String
Dim strConn As String
Dim strRtn As String = ""
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=No;Imex=1"";"
conString = String.Format(strConn, path)
Dim con As OleDbConnection = New OleDbConnection(conString)
con.Open()
Dim schemaTable As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
con.Close()
Dim ds As DataSet = New DataSet()
Dim row As DataRow
Dim tableName As String
Dim sql As String
Dim oda As OleDbDataAdapter
Dim table As DataTable
For Each row In schemaTable.Rows
tableName = row("TABLE_NAME").ToString()
sql = String.Format("SELECT * FROM [{0}]", tableName)
oda = New OleDbDataAdapter(sql, con)
table = New DataTable(tableName)

strRtn = strRtn & "SheetName:" & tableName & vbCrLf

Try
oda.Fill(table)
ds.Tables.Add(table)
Dim dr As DataRow
For r = 0 To ds.Tables(0).Rows.Count - 1 'Show results in output window
dr = ds.Tables(0).Rows(r)
For c = 0 To dr.ItemArray.Length - 1
If dr.ItemArray(c).ToString <> "" Then
strRtn = strRtn & "(" & c & "/" & r & ")" & dr.ItemArray(c).ToString & vbCrLf
End If
Next
Next

Catch ex As Exception
End Try
Next
Return strRtn
End Function
End Class

以下のページを参考にさせていただきました。多謝。
http://d.hatena.ne.jp/nagakura_eil/20080716/p1
http://support.microsoft.com/kb/316934/ja
http://support.microsoft.com/kb/257819/ja