0

我尝试了PHPExcel下载包test 01。该示例使用对象来指定哪个单元格包含什么,并生成一个excel文件。

此外,我尝试了以下代码从数据库生成 excel 文件:-

    $file_type = "vnd.ms-excel";
    $file_ending = "xls";


//header info for browser: determines file type ('.doc' or '.xls')
header("Content-Type: application/$file_type");
header("Content-Disposition: attachment; filename=$file_name.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");

$xls_header = '<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf-8" />
</head>
<body>
<table border="1" align="center">';

$xls_footer = '</table>
</body>
</html>';
print $xls_header;

/*  Start of Formatting for  Excel  */


    /*  FORMATTING FOR EXCEL DOCUMENTS ('.xls')   */
    //create title with timestamp:
    if ($Use_Title == 1)
    {
        echo "<tr><td colspan='".mssql_num_fields($result)."'>";
        echo("$title");
        echo "</td></tr>";
    }
    //define separator (defines columns in excel & tabs in word)
    //$sep = "\t"; //tabbed character

        echo "<tr>";
    //start of printing column names as names of MySQL fields
    for ($i = 0; $i < mssql_num_fields($result); $i++)
    {
        echo "<td>";
        echo mssql_field_name($result,$i);
        echo "</td>";
    }
    print("</tr>");
    //end of printing column names

    //start while loop to get data
    while($row = mssql_fetch_array($result))
    {
        $schema_insert .= "<tr>";
        //set_time_limit(60); // HaRa
        $schema_insert = "";
        for($j=0; $j< mssql_num_fields($result);$j++)
        {
            $schema_insert .= "<td>";
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
            $schema_insert .= "</td>";
        }
        $schema_insert .= "<tr>";
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        //following fix suggested by Josue (thanks, Josue!)
        //this corrects output in excel when table fields contain \n or \r
        //these two characters are now replaced with a space
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }
    print $xls_footer;

但 excel 程序告诉我它不是一个真正的 excel 文件。如果我想用数据库中的数据为 xls 和 xlsx 格式生成真正的 excel 文件,有什么好的例子吗?

谢谢!

4

0 回答 0