Excelで読めるHTMLを書く

Webサービスなどから、Excelで読めるHTMLを出力する場合、
以下の2行をヘッダで出力すればいいのは有名な話。
Content-Type: application/vnd.ms-excel
Content-Disposition: attachment; filename="file.xls"

しかし、今回も同じ技を使おうと思って困ったことになった。
それは、改行が反映されない。
Officeは2000までしか持ってないので、他のバージョンはどうなのかわからないけれど、
MSのことなので、この仕様(不具合)は2007でも継承されているに違いない(かもしれない)。
tdセル内に<br>を書くと行が分離してしまう。
純粋にプレーンなtableを書くとこうなってしまうらしい。
仕方が無いので、ExcelでHTMLを出力させ、改行が反映できるHTMLファイルのテンプレートを作ることにした。
以下がそのコード

<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=UTF-8">
<style>
<!--tr
	{mso-height-source:auto;
	mso-ruby-visibility:none;}
br
	{mso-data-placement:same-cell;}
.style0
	{mso-number-format:General;
	text-align:general;
	vertical-align:bottom;
	white-space:nowrap;
	mso-rotate:0;
	mso-background-source:auto;
	mso-pattern:auto;
	color:windowtext;
	font-size:11.0pt;
	font-weight:400;
	font-style:normal;
	text-decoration:none;
	font-family:"MS Pゴシック";
	mso-generic-font-family:auto;
	mso-font-charset:128;
	border:none;
	mso-protection:locked visible;
	mso-style-name:標準;
	mso-style-id:0;}
td
	{mso-style-parent:style0;
	mso-ignore:padding;
	color:windowtext;
	font-size:11.0pt;
	font-weight:400;
	font-style:normal;
	text-decoration:none;
	font-family:"MS Pゴシック";
	mso-generic-font-family:auto;
	mso-font-charset:128;
	mso-number-format:General;
	text-align:general;
	vertical-align:bottom;
	border:none;
	mso-background-source:auto;
	mso-pattern:auto;
	mso-protection:locked visible;
	white-space:nowrap;
	mso-rotate:0;}
.xl24
	{mso-style-parent:style0;
	white-space:normal;}
-->
</style>
<!--[if gte mso 9]><xml>
 <x:ExcelWorkbook>
  <x:ExcelWorksheets>
   <x:ExcelWorksheet>
    <x:Name>Sheet1</x:Name>
    <x:WorksheetOptions>
     <x:Selected/>
    </x:WorksheetOptions>
   </x:ExcelWorksheet>
  </x:ExcelWorksheets>
 </x:ExcelWorkbook>
</xml><![endif]-->
</head>
<body>
<table>
 <tr>
  <td class=xl24>あ<br>い</td>
 </tr>
</table>
</body>
</html>

tdタグのxl24というクラスがあることで改行が反映されるらしい。
表示が1行のみになってしまうが、データとしては問題ないらしい。
もう少し削れそうだけど、テーブルの中身さえスッキリすれば、テンプレートとして問題ないので今はここまで。
この方法はMSのExcel用のものなので、OpenOfficeOrgのCalcではやはり分離する。

Excelで読めるHTMLを書く」への1件のフィードバック

通りすがり へ返信する コメントをキャンセル

メールアドレスが公開されることはありません。 が付いている欄は必須項目です