使用PHP怎么导出excel数据

发布时间:2021-04-02 17:01:49 作者:Leah
来源:亿速云 阅读:159

这篇文章将为大家详细讲解有关使用PHP怎么导出excel数据,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

class Excel_XML
{
//定于私有变量,顶部标签
private $header = "<?xml version=\"1.0\" encoding=\"%s\"?\>\n<Workbook xmlns=\"urn:schemas-microsoft-com:
office:spreadsheet\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:
office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
//底部标签
private $footer = "</Workbook>";
//定于行数组
private $lines = array();
//设置编码
private $sEncoding;
//设置类型
private $bConvertTypes;
//设置sheet名称
private $sWorksheetTitle;
//构造函数
public function __construct(
 $sEncoding = 'UTF-8',$bConvertTypes = false,$sWorksheetTitle = 'Table1')
{
$this->bConvertTypes = $bConvertTypes;
$this->setEncoding($sEncoding);
$this->setWorksheetTitle($sWorksheetTitle);
}
//设置编码,在构造函数里面默认的事UTF-8格式
public function setEncoding($sEncoding)
{
$this->sEncoding = $sEncoding;
}
//设置excel的头
public function setWorksheetTitle ($title)
{
$title = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $title);
$title = substr ($title, 0, 31);
$this->sWorksheetTitle = $title;
}
//增加行函数(关键函数)
private function addRow ($array)
{
$cells = ""; //设置每个单元为空
foreach ($array as $k => $v)
{
 $type = 'String'; //默认类型是字符串
 if ($this->bConvertTypes === true && is_numeric($v)): //判断类型
 { $type = 'Number'; }
 $v = htmlentities($v, ENT_COMPAT, $this->sEncoding);
 $cells .= "<Cell><Data ss:Type=\"$type\">" . $v . "</Data></Cell>\n";
}
 $this->lines[] = "<Row>\n" . $cells . "</Row>\n"; //写入数组
}
//增加数组
public function addArray ($array)
{
foreach ($array as $k => $v)
 {$this->addRow ($v);}
}
//导出xml
public function generateXML ($filename = 'excel-export')
{
$filename = preg_replace('/[^aA-zZ0-9\_\-]/', '', $filename);
header("Content-Type: application/vnd.ms-excel; charset=" . $this->sEncoding);
header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");
echo stripslashes (sprintf($this->header, $this->sEncoding));
echo "\n<Worksheet ss:Name=\"" . $this->sWorksheetTitle . "\">\n<Table>\n";
foreach ($this->lines as $line)
echo $line;
echo "</Table>\n</Worksheet>\n";
echo $this->footer;
}
}

原理很简单,就是把数据数组,读出来,再用XML的标签封上,在用php自带的header()函数告诉游览器,就可以了。

调用:

public function import()
{
 $data = array(
 1 => array ('学校名称',"队伍名称")
 );
 foreach($this->team as $key=>$value)
 {
  array_push($data,array($key, $value));
 }
 $xls = new Excel_XML('UTF-8', false, 'My Test Sheet'); //实例化函数
 $xls->addArray($data);
 $xls->generateXML('school'); //导出并设置名称
}

关于使用PHP怎么导出excel数据就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 导出Excel数据(续)
  2. php如何导出excel

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php excel

上一篇:如何在Laravel中使用日志

下一篇:怎么在PHP中使用clone克隆对象

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》