php中怎么导出excel

发布时间:2021-06-29 16:44:59 作者:Leah
来源:亿速云 阅读:106

php中怎么导出excel,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

方法一

<?php
$title = array('Engineer', 'Team', 'Type');
//导出准备
ob_get_clean();
ob_start();
echo implode("\t", $title),"\n";

$list = array(); // 要导出的列表数据
if (!empty($list) && is_array($list)) {
    foreach ($list as $k => &$v) {
        echo implode("\t", $v),"\n";
    }
}

$filename = 'lists.xls';
header('Content-Disposition: attachment; filename='.$filename);
header('Accept-Ranges:bytes');
header('Content-Length:' . ob_get_length());
header('Content-Type:application/vnd.ms-excel');
ob_end_flush();
//设置头信息
header('Content-Disposition:attachment;filename=' . basename($filename));
header('Content-Length:' . filesize($filename));
//读取文件并写入到输出缓冲
readfile($filename);

这种方法好处就是用PHP代码处理直接导出,弊端就是无法自行定义表格样式,结果如下(我用实际数据来导出所以字段比较多,不要在意)
php中怎么导出excel

方法二

<?php
// 下载,请求头设置
header("Content-type:application/octet-stream");
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=lists.xls");
header('Content-Type:application/vnd.ms-excel');
header("Pragma: no-cache");
header("Expires: 0");

$title = array('Engineer', 'Team', 'Type'); // excel表头
$list = array(); // 要导出的列表
?>

<html>
<head>
    <title>导出</title>
</head>
<body>
    <table border="1" cellpadding="3" cellspacing="0" bordercolor="#C0C0C0">
        <tr>
            <?php
                foreach ($title as $k => $v) {
                    echo "<th>{$v}</th>";
                }
            ?>
        </tr>
        <?php
            foreach ($list as $k => $v) {
                echo "<tr>";
                foreach ($v as $key => $val) {
                    echo "<td>{$val}</td>";
                }
                echo "</tr>";
            }
        ?>
    </table>
</body>
</html>

这种方法在定义请求头部分差不多,就是需要些html来自定义样式,但是美观很多

php中怎么导出excel

但这两种方式貌似都只能导出xls的文件,无法导出xlsx,而且导出的xls文件在打开的时候都有以下提示,不知道怎么解决....知道的朋友烦请指教,谢谢

php中怎么导出excel

关于php中怎么导出excel问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. php如何导出excel
  2. PHP如何导出Excel的优化详解

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

php

上一篇:PHP中怎么获取类和对象的属性字段

下一篇:php中怎么使用xhprof 性能分析工具

相关阅读

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

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