欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

php 生成excel xls文档

程序员文章站 2022-05-15 16:58:13
...
php教程 生成excel xls文档

方法1 - 使用HTTP头

至于在MS Word中所述,您需要格式化的HTML / PHP页面使用Excel友好CSS和标头信息

添加到您的PHP脚本。
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment;Filename=document_name.xls");

echo "

";
echo "

charset=Windows-1252">";
echo "

";
echo "testdata1 t testdata2 t n ";
echo "";
echo "";
?>

方法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);