php教程 生成excel xls文檔
方法1 - 使用HTTP頭
至於在MS Word中所述,您需要格式化的HTML / PHP頁面使用Excel友好CSS和標頭信息
添加到您的PHP腳本。
<?php
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment;Filename=document_name.xls");
echo "<html>";
echo "<meta http-equiv="Content-Type" content="text/html;
charset=Windows-1252">";
echo "<body>";
echo "<b>testdata1</b> t <u>testdata2</u> t n ";
echo "</body>";
echo "</html>";
?>
方法2 - 使用COM對象
請注意,在服務器運行下面必須有MS Excel中所述的代碼安裝。
我們使用一個文件保存到臨時目錄第一,作為MS Word的同樣的做法。
//Create new COM object – excel.application
$xl = new COM("excel.application");
//Hide MS Excel application window
$xl->Visible = 0;
//Create new document
$xlBook = $xl->Workbooks->Add();
//Create Sheet 1
$xlBook->Worksheets(1)->Name = "Worksheet 1";
$xlBook->Worksheets(1)->Select;
//Set Width & Height
$xl->ActiveSheet->Range("A1:A1")->ColumnWidth = 10.0;
$xl->ActiveSheet->Range("B1:B1")->ColumnWidth = 13.0;
//Add text
$xl->ActiveSheet->Cells(1,1)->Value = "TEXT";
$xl->ActiveSheet->Cells(1,1)->Font->Bold = True;
//Save document
$filename = tempnam(sys_get_temp_dir(), "excel");
$xlBook->SaveAs($filename);
//Close and quit
unset( $xlBook);
$xl->ActiveWorkBook->Close();
$xl->Quit();
unset( $xl );
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment;Filename=document_name.xls");
// Send file to browser
readfile($filename);
unlink($filename);