首页 > 代码库 > 使用原生php将数据库数据导出到excel文件中

使用原生php将数据库数据导出到excel文件中

最近在工作中遇到一个需求,需要将数据库中的数据导出到excel文件中,并下载excel文件。因为以前没做过,所以就百度了一下,

网上说的大多是使用PHPExcel类来操作excel文件,这还要去下载这个类才能使用,而我只想使用原生的php,不想那么麻烦,好在

也有网友说到关于原生php生成excel文件的方法,其实很简单,下面把我结合网上资料自己实践的代码分享一下。

一般我们这种导数据的操作都是通过用户在网页页面上点击某个按钮触发相应js方法,然后请求php接口来实现的,所以主要有两种

方法来完成这种需求。

方法1:直接在js代码中使用window.open()打开php接口的url,即可将php生成的excel文件下载下来。

php接口代码如下:

$mysqli = mysqli_connect(‘localhost‘, ‘root‘, ‘123456‘, ‘test‘);
$sql = ‘select * from country‘;
$res = mysqli_query($mysqli, $sql);
header("Content-type:application/vnd.ms-excel"); 
header("Content-Disposition:filename=country.xls"); 
echo "code\t";
echo "name\t";
echo "population\t\n";
if(mysqli_num_rows($res) > 0) {
    while($row = mysqli_fetch_array($res)) {
        echo $row[‘code‘]."\t";
        echo $row[‘name‘]."\t";
        echo $row[‘population‘]."\t\n";
    }
}

 

方法2:php接口中先把生成的excel文件保存在服务器中,然后把文件路径返回给js,js再使用window.open()打开文件路径即可下载。

php接口代码如下:

$mysqli = mysqli_connect(‘localhost‘, ‘root‘, ‘123456‘, ‘test‘);
$sql = ‘select * from country‘;
$res = mysqli_query($mysqli, $sql);
$file = fopen(‘./country.xls‘, ‘w‘);
fwrite($file, "code\tname\tpopulation\t\n");
if(mysqli_num_rows($res) > 0) {
    while($row = mysqli_fetch_array($res)) {
        fwrite($file, $row[‘code‘]."\t".$row[‘name‘]."\t".$row[‘population‘]."\t\n");
    }
}
fclose($file);
echo ‘http://www.jtw.com/....../country.xls‘;//这里返回文件路径给js

 

两种方法很类似,都能实现将数据库中的数据导出到excel文件中并下载文件,最终文件截图如下:

技术分享

 

使用原生php将数据库数据导出到excel文件中