Home > Backend Development > PHP Tutorial > PHP file exports database data to Excel table code introduction

PHP file exports database data to Excel table code introduction

不言
Release: 2023-04-04 15:46:02
forward
4343 people have browsed it

The content of this article is about the code introduction of php files to export database data to Excel tables. It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.

The database contains too much content, is it too troublesome to copy and paste?

Then use code to implement it. Once the code is written, isn’t it easy to export? You can export it by visiting.

excel.php

<?php
    error_reporting(E_ALL ^ E_DEPRECATED);
    $localhost = &#39;数据库地址&#39;;
    $dbname = &#39;数据库名&#39;;
    $dbuser = &#39;数据库账号&#39;;
    $dbpwd = &#39;数据库密码&#39;;
    $tbname = "需要导出的数据库表名";

    ob_end_clean();
    header(&#39;Content-type: text/html; charset=utf-8&#39;);
    header("Content-type:application/vnd.ms-excel;charset=UTF-8"); 
    header("Content-Disposition:filename=data.xls");// 文件名自己改,默认data.xls

    $conn = mysql_connect($localhost,$dbuser,$dbpwd) or die("连接数据库失败");
    mysql_select_db($dbname, $conn);
    mysql_query("set names &#39;UTF-8&#39;");

    $result=mysql_query("SELECT * FROM $tbname");
    echo "<table>";
    echo "<tr>";
    echo "<th>A1单元格</th>";
    echo "<th>B1单元格</th>";
    echo "<th>C1单元格</th>";
    echo "<th>D1单元格</th>";
    echo "</tr>";
    echo "</table>";
    while($row=mysql_fetch_array($result)){
        //下面data改成你自己数据库对应的字段
        $data1 = $row["data1"];
        $data2 = $row["data2"];
        $data3 = $row["data3"];
        $data4 = $row["data4"];
        
        //输出字段的数据到单元格
        //下面data改成你自己数据库对应的字段
        echo "<table>";
        echo "<tr>";
            echo "<td>$data1</td>";
            echo "<td>$data2</td>";
            echo "<td>$data3</td>";
            echo "<td>$data4</td>";
        echo "</tr>";
        echo "</table>";
    }
?>
Copy after login

Then visit excel.php and the form will pop up to download.

The above is the detailed content of PHP file exports database data to Excel table code introduction. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template