広告に関する明記

当ブログにはアフィリエイトリンクが含まれます。

プログラム

asp.netでExcelを読込む方法

仕事でExcelファイルをasp.netで読み込む必要があったのだけど、
本もネットも読み込んでいるのはTXTかCSVばっかり。
そりゃ、データのやりとりなら
わざわざExcel使うより、効率も互換性もいいからだろうけど、
じゃぁ、Excelはどうやるんだ?
と苦労したので(いや、そうでもないか?)
メモ代わりに残す。


aspx側


<%@ Page Language="VB" AutoEventWireup="false" _
CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC _
"-//W3C//DTD XHTML 1.0 Transitional//EN" _
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Excel読込</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="Table1" align="center" border="1" width="600px" cellpadding="10">
<tr>
<td>
<fieldset>
<legend>アップロード</legend>
<table class="Table2" border="0">
<tr>
<td nowrap class ="TableHR">
アップロード先指定
</td>
<td nowrap>
<!--参照ボタン-->
<input class="Btn" type="file" name="txtUp" _
style="width: 450px" runat="server" id="txtUp" />
</td>
</tr>
</table>
</fieldset>
<table class="Table2" border="0">
<!--ボタン-->
<tr>
<td nowrap colspan=10 align="right" style="height: 54px"> _
<br />
<input name="txtIns" type="hidden" id="txtIns" style="width: 1px; _
left: 0px; top: 6px;" tabindex="-1" _
runat="server" />
<asp:Button ID="BtnUpload" runat="server" cssclass="Btn" _
Style="position: relative; left: 0px; top: 6px;" Text=" 登 録 " _
OnClientClick="fInsertConfirm('アップロード');" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>


aspx.vb

Imports Com.Excel
Imports Microsoft.Office.Interop.Excel
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub BtnUpload_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles BtnUpload.Click
Dim Full_Pass As String 'フルパス
'Excelクラスの定義
Dim xw As New ExcelWorker
Dim wb As Workbook = Nothing
Dim wss As Sheets = Nothing
Dim ws As Worksheet = Nothing
Dim ws2 As Worksheet = Nothing
Dim wcs As Range = Nothing
Dim witchPassword As String = パスワード
'フルパス取得
Full_Pass = Me.txtUp.PostedFile.FileName
Try
'Excelファイルをオープン
xw.SetBookPath = Full_Pass
wb = xw.BookOpen(witchPassword)
ws = wb.Sheets("aaa")
ws.Select()
Dim j As Integer = 1
While Not ws.Cells(j, 1).Value = Nothing
MsgBox(ws.Cells(j, 1).Value)
j = j + 1
End While
Catch ex As Exception
Finally
Try
'シートの解放
If Not ws Is Nothing Then xw.MRComObject( _
CType(ws, System.Object))
If Not wss Is Nothing Then xw.MRComObject( _
CType(wss, System.Object))
'Excelの終了(保存して終了)
xw.Dispose(True, wb)
Catch ex As Exception
End Try
'Excelクラスの解放
xw = Nothing
End Try
End Sub
End Class

-プログラム