使用php导出到excel

时间:2013-12-05 01:05:41

标签: php excel

我正在尝试使用PHP在Excel中生成报告。下面是我的代码,它正在运行,但我没有得到我希望在Excel电子表格中显示的正确输出。似乎包含了我表单中的所有数据。我想要的只是我要打印的数据库中的数据。你能帮我解决我的问题吗?

<?php 
    //this is my code for downloading my files into excel..
    if (isset($_POST['download']))
        include("db.php");

    {
        //$file="document_name" . date('Ymd') . ".xls";

        //header("Content-type: application/vnd.ms-excel");// file extension name
        //header("Content-Disposition: attachment; filename=$file");
        $query = "SELECT * FROM user"; 
        $result = mysql_query($query) or die(mysql_error());
        $filename ="excelreport.xls";

        while($row = mysql_fetch_array($result)) {

        }

        header('Content-type: application/ms-excel');
        header('Content-Disposition: attachment; filename='.$filename);        
    }
?>

2 个答案:

答案 0 :(得分:0)

如果你想简单地转储数据而不进行任何格式化,你应该使用CSV格式,也可以在Excel中打开。参见fputcsv()函数

如果您想创建有效的Excel文件,则应尝试使用PHPExcel库

答案 1 :(得分:0)

有一些PEAR包使Excel导出相当容易。我已经在以前需要导出数据库信息的一些项目中使用过它。许多服务器已经安装了PEAR,但您可能需要添加此特定包:

http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro.php