php 生成excel xls文档

PHP和COM
如果你是一名冒险份子,而且你正在使用CGI、ISAPI或Apache模块版本的Windows系统上运行着PHP,那么你也可以获得系统的COM功能。现在,解释COM的工作留给了微软和那些大部头的图书来完成。然而,知道点COM也没什么错,下面有一个普通的代码小片断。
这代码小片断使用PHP在后台启动Microsoft
Word、打开一个新文件、键入一些文本、保存该文件然后关闭应用程序: ? //
create a reference to a new COM component (Word) $word = new
COM(“word.application”) or die(“Cant start Word!”); // print the version
of Word thats now in use echo “Loading Word, v. {$word-Version}br”; //
set the visibility of the application to 0 (false) // to open the
application in the forefront, use 1 (true) $word-Visible = 0; // create
a new document in Word $word-Documents-Add(); // add text to the new
document $word-Selection-TypeText(“Testing 1-2-3…”); //save the
document in the Windows temp directory
$word-Documents[1]-SaveAs(“/Windows/temp/comtest.doc”); // close the
connection to the COM component $word-Quit(); // print another message
to the screen echo “Check for the file…”; ?
假设你正在运行一个内联网Web站点,该站点把数据存放在Microsoft SQL
Server数据库内,你的用户需要Excel格式的数据。那么,你可以让PHP执行必要的SQL查询并且格式化输出结果,然后使用COM启动Excel,把数据传输给它,最后再把文件存储到用户的桌面系统内。

方法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> <u>testdata2</u> “;
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);

You can leave a response, or trackback from your own site.

Leave a Reply

网站地图xml地图