如标题所述 - 我编写了一个小脚本,可以将包含数据的 SQL 生成表导出到 Excel 可读的 .xls
文件中。但是,当我导出数据时,出于某种原因,页脚和页眉也被转储到包含图像和所有内容的 .xls
文件中。
这是我导出 MySQL 数据的脚本:
if(isset($_POST['download']))
{
$q = "SELECT * FROM completed_tasks ORDER BY PRIORITY DESC";
$result = mysqli_query($conn, $q);
if(mysqli_num_rows($result) > 0)
{
$output .= "<table class='sqltable'>
<tr class='sqltable'>
<th class='sqltable'>From:</th>
<th class='sqltable'>Department:</th>
<th class='sqltable'>Name of the task:</th>
<th class='sqltable'>Description:</th>
<th class='sqltable'>Priority:</th>
<th class='sqltable'>Time elapsed:</th>
<th class='sqltable'>Completed by:</th>
<th class='sqltable'>Notes:</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc())
{
$output .= "<tr class='sqltable'>";
$output .= "<td class='sqlcell'>".$row["FROM"]."</td>";
$output .= "<td class='sqlcell'>".$row["DEPT"]." </td>"
$output .= "<td class='sqlcell'>".$row["TASK_NAME"]."</td>";
$output .= "<td class='sqlcell'>".$row["TASK"]."</td>";
$output .= "<td class='sqlcell'>". $row["PRIORITY"]."</td>";
$output .= "<td class='sqlcell'>".$row["TIME_COMPLETED"]."</td>";
$output .= "<td class='sqlcell'>".$row["COMPLETED_BY"]."</td>";
$output .= "<td class='sqlcell'>".$row["TASK_RESOLVE"]."</td>";
$output .= "</tr>";
}
$output .= "</table>";
header('Content-Type: application/xls');
header('Content-Disposition: attachment; filename=download.xls');
echo $output;
}
编辑:我刚刚意识到我生成的 .xls
文件也在寻找 .css
样式配置。
最佳答案
在 php 中使用 PHPSpreadsheet 构建 excell
PHPSpreadSheet is a library for Excell An open source project Build support Microsoft Excell 2007
这是链接 PHPSpreadSheet 从 composer 安装在命令行上
composer require phpoffice/phpexcel
你的代码应该是这样的
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$range = range(65,90);
if(mysqli_num_rows($result) > 0)
{
$sheet->setCellValue('A1', 'From');
$sheet->setCellValue('B1', 'Department');
$sheet->setCellValue('C1', 'Name of the task');
$sheet->setCellValue('D1', 'Description');
$sheet->setCellValue('E1', 'Priority:');
$sheet->setCellValue('F1', 'Time elapsed');
$sheet->setCellValue('G1', 'Notes:');
// output data of each row
while($row = $result->fetch_assoc())
{
// Do somme logic to store data to excell
}
header('Content-Type: application/xls');
header('Content-Disposition: attachment; filename=download.xls');
$writer = new Xls($spreadsheet);
$writer->save('php://stdout');
关于php - 我用于将 MySQL 模式导出到 .xls 的 PHP 脚本转储 HTML 工件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55142596/