单击按钮下载文件并导出到Excel

时间:2015-10-24 01:07:19

标签: php html excel

(1)表:学生
    enter image description here

(2) functions.php

<?php
function DisplaySearchStudentSummaryForm()
{
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <table class="displaytable">
        <tr>
            <td width="150" class="dtdr" align="right">Student Name : </td>
            <td width="450" class="dtd"><input type="text" name="studentname" size="30"/></td>
        </tr>
    </table>
    <table>
        <tr align="center" valign="top">
            <td width="300"><input type="submit" name="submit" value="Export" class="buttons"></td>
            <td width="300"><input name="reset" type="reset" id="reset" value="Reset" class="buttons"></td>
        </tr>  
   </table>
</form>
<?php
}

function SearchStudentSummary($studentname)
{
    include_once('dbconnection.php');

    $q = "SELECT studentname, grade FROM student WHERE studentname like '$studentname%'";
    $r = mysqli_query($dbc, $q);

    while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
    {
        $record[] = $row;
    }

    return $record;
}

function ExportToExcel($record)
{
    [?]
}
?>

(3) test.php

<?php
session_start();
if(!isset($_SESSION["studentname"]))
{
    header("Location: index.php");
}    

include_once('functions.php');
?>

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
<table width="1100" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td>
        <?php
            if(isset($_POST['submit']) && ($_POST['submit'] == 'Export'))
            {
                $studentname = $_POST['studentname'];
                $record = SearchStudentSummary($studentname); 
                ExportToExcel($record);
            }
            else
            {
                DisplaySearchStudentSummaryForm();
            }
        ?>
        </td>
    </tr>
<table>
</body>
</html>

(4)目前我的输出如下图所示: enter image description here

(5)现在我输入&#34; Wong&#34;在studentname文本字段中,单击“导出”按钮:
    - &GT;找到包含单词&#34; Wong&#34;。
的学生表     - &GT;使用PHP_XLSXWriter库下载excel文件     - &GT;使用PHP_XLSXWriter库将结果导出到excel文件。

(6)XLSXWriter代码:

<?php
include('./PHP_XLSXWriter-master/xlsxwriter.class.php');

//---Download excel file---
$filename = "student.xlsx";
header('Content-Disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');

//---Export excel file---
$header = array('studentname'=>'string', 'grade'=>'string');
for($i = 0; $i < count($record); $i++)
{
    $data = array(array($record[$i]['studentname'],$record[$i]['grade']));
}

$writer = new XLSXWriter();
$writer->writeSheet($data,'Sheet1',$header);
$writer->writeToStdOut();
exit(0);
?>

我不知道如何将我的XLSXWriter代码放入[?]部分的ExportToExcel()函数中。有人能帮助我吗?

0 个答案:

没有答案