使用php创建Excel文件

时间:2015-04-13 17:06:14

标签: php xml excel

您好朋友我正在尝试使用php创建excel文件...但是由于标题("位置:userhome.php")而导致其创建问题(我需要在执行后重定向该标头)代码)你能给我任何建议吗? 这是我的代码:

<form method="post" >
    Book title: <input type="text" name="BookTitle" id="name" />
    Book symmary: <textarea name="BookSymmary" id="email" ></textarea>

    <input type="submit" name="submit" value="Send Form" />
</form>

    <?php
if (isset($_POST['submit'])) {
    $BookTitle = $_POST['BookTitle'];
    $BookSymmary = $_POST['BookSymmary'];
    $filename = 'document_name.xls';

    if ((!empty($BookTitle)) && (!empty($BookSymmary))) {

        header("Content-type: application/vnd.ms-excel");
        header("Content-Disposition: attachment;Filename=" . $filename);

        echo "<html>";
        echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
        echo "<body>";
        ?>
        <div>
            <table>
                <caption>Book printed</caption>               
                <thead>
                    <tr>
                        <th>Book title</th>
                        <th>Book summary</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><?php echo $BookTitle ?></td>
                        <td><?php echo $BookSymmary ?></td>
                    </tr>
                </tbody>
            </table>
        </div>
        <?php
        echo "</body>";
        echo "</html>";
    } else {
        echo "Please enter something..";
    }
}
 header("Location: userhome.php"); 
?>

2 个答案:

答案 0 :(得分:1)

你最后不能使用header,因为事先已有输出。来自文档:

  

请记住,在发送任何实际输出之前,必须先调用 header(),无论是普通HTML标记,文件中的空行还是PHP。

如果你想重定向,你可以改为输出一些简单的JavaScript:

<script>
document.location.href = 'userhome.php';
</script>

答案 1 :(得分:0)

你好朋友我找到了解决方案......可能对某些人有用......

$sep = "\t";        //tabbed character
$fp = fopen('registrars.xls', "w");

$schema_insert_rows = "";
//printing column names      
    $schema_insert_rows.="Book Name" . $sep;
    $schema_insert_rows.="Book Summary" . $sep;
    $schema_insert_rows.="\n";
    fwrite($fp, $schema_insert_rows);

// printing data:
$schema_insert_rows = "";
    $schema_insert_rows .= "sandy" . $sep;
    $schema_insert_rows .= "Summaaarrryyy" . $sep;
    $schema_insert_rows .= "\n";
    fwrite($fp, $schema_insert_rows);

fclose($fp);