こんにちわ。
本当に久しぶりの更新になってしまいました。
(まぁ、いつものことなんですけど…)
今回は、現在クライアント様からデータをcsv方式ではなく、
asp(vbscript)にてエクセルに吐き出してほしいという要望があり、
簡易に吐き出す方法を記載したいと思います。
<%@ language=vbscript %>
<%
'------------------------------------
'本来はここにデータベースとつなげたり
'引数の処理したりをします
'今回、データベースから引っ張ってきた
'レコードセットをObjRS1とします
'------------------------------------
%>
<%
response.buffer = true
response.ContentType = "application/vnd.ms-excel"
response.AddHeader "content-disposition", "inline; filename=test.xls"
%>
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv=Content-Type content="text/html; charset=shift_jis">
<meta name=ProgId content=Excel.Sheet>
<meta name=Generator content="Microsoft Excel 10">
<title>タイトル</title>
</head>
<body>
<table border="1">
<tr>
<th style="background-color: #add8e6" width="70">ID</th>
<th style="background-color: #add8e6" width="70">名前</th>
</tr>
<%
Do Until ObjRS1.EOF
%>
<tr>
<td style='mso-number-format:"\@";'><%=ObjRS1("ID")%></th>
<td><%=ObjRS1("UserName")%></th>
</tr>
<%
ObjRS1.MoveNext
Loop
%>
</table>
</body>
</html>
<%
response.flush
response.end
%>
はい。意外とまとめてしまうとこんなものなのです。
要はhtml方式で作成して、ヘッダー部分でEXCELとして認識させる
という方式なのです。
response.buffer から headの閉じタグまではお約束事。
最後のresponse.flush、response.endもお約束事です。
あとは何てこと無い、データをテーブルで作成・表示しているだけなのです。
また、 style=’mso-number-format:”\@”;’ というスタイルを入れていますが、
これは、EXCELで開いた際に、00001という頭に0が付く文字については、
EXCELでは削除してしまうので、文字列として認識させるために、
スタイルを入れています。
お試しあれ。
2014.11.17追加
【続報】webからエクセルファイルに吐き出す方法
も、ご覧ください。