Home  >  Article  >  Backend Development  >  在PHP中操作Excel实例代码_PHP

在PHP中操作Excel实例代码_PHP

WBOY
WBOYOriginal
2016-06-01 12:20:07787browse
复制代码 代码如下:
//指定页面编码,防止出现中文乱码的情形
header('Content-type: text/html; charset=gb2312');

//启动Excel
$ms_excel=new COM("excel.application") or die("不能打开Excel应用程序");

//在网页中显示当前的Excel版本
echo "Excel版本:{$ms_excel->Version}\n";

//新建一个工作簿
$ms_excel->Application->Workbooks->Add() or die("不能添加新工作簿");

//在工作簿的工作表Sheet1中单元格A1中输入文本
$ms_excel->Worksheets("Sheet1")->Range("A1")->Value="测试";

//保存工作簿,如果没有指定路径,则默认保存在我的文档中
$ms_excel->Workbooks(1)->SaveAs("php_excel_test.xls");

//关闭工作簿
$ms_excel->Quit();

//清空对象
$ms_excel=null;
?>

在htdocs文件夹中将该文件保存为“excelsample.php”。打开浏览器,在地址栏中输入:

http://localhost/excelsample.php

此时,将会在页面中显示当前的Excel版本,同时创建名为php_excel_test.xls的工作簿并在工作表Sheet1单元格A1中输入“测试”。
打开工作簿php_excel_test.xls,在单元格A1中将会看到已经输入了“测试”。
注:为防止出现乱码,在代码开始设置了编码格式,同时在保存文件时选择保存为gb2312格式。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn