PHP HTML 表作为 Excel .xls 文件



我在PHP中有一些sripts可以创建一个表并将其另存为和xls文件。一切都很完美,编辑工作表内的信息。但是几天前,当我打开其中一个文件并编辑单元格数据并尝试保存时,Microsoft Excel 尝试将文件另存为 HTML,即使文件扩展名是xls

$table = "<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<table>
Some table rows with table data
</table>
</body>
</html>";

我将带有fopenfwritefclose$table变量保存在一个文件中,然后下载该文件。

我也尝试直接下载文件,并且总是在编辑时,Excel尝试将其另存为HTML。

我一直在寻找解决方案,但没有任何帮助。知道如何解决吗?

有几个选项可以将HTML表导出到xls或xlsx。

第一个,回显右标题下的内容。这将在 excel 中生成大量警告,但 xls 将是可读的:

<?php
$excel_file="output.xls";
$table = "<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<table>
<tr><td>Some </td><td>table</td> <td>rows</td> <td>with</td> <td>table</td> <td>data</td></tr>
</table>
</body>
</html>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=".$excel_file."");
echo $table;
?>

第二个更流畅一些,使用现有的库,如PhpSpreadsheet。你可以在他们的github页面上找到非常简洁的基本示例:https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/Basic/01_Simple.php

第三个,使用来自SheetJS JS-XLSX库的JS片段。在这里,您可以看到一个基本示例:

<!DOCTYPE html>
<html>
<head>
<title>SheetJS JS-XLSX In-Browser HTML Table Export Demo</title>
<meta charset="utf-8" />
</head>
<body>
<![if gt IE 9]>
<script type="text/javascript" src="//unpkg.com/xlsx/dist/shim.min.js"></script>
<script type="text/javascript" src="//unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<script type="text/javascript" src="//unpkg.com/blob.js@1.0.1/Blob.js"></script>
<script type="text/javascript" src="//unpkg.com/file-saver@1.3.3/FileSaver.js"></script>
<![endif]>
<script>
function doit(type, fn, dl) {
var elt = document.getElementById('data-table');
var wb = XLSX.utils.table_to_book(elt, {sheet:"Sheet JS"});
return dl ?
XLSX.write(wb, {bookType:type, bookSST:true, type: 'base64'}) :
XLSX.writeFile(wb, fn || ('SheetJSTableExport.' + (type || 'xlsx')));
}
</script>
<div id="container">
<table id="data-table">
<tr><td>Sample1</td><td>Sample2</td><td>Sample3</td></tr>
<tr><td>Sample4</td><td>Sample5</td><td>Sample6</td></tr>
<tr><td>Sample7</td><td>Sample8</td><td>Sample9</td></tr>
</table>
</div>
<table>
<tr>
<td>
<p id="xportxlsx" class="xport"><input type="submit" value="Export to XLSX!" onclick="doit('xlsx');"></p>
</td></tr>
</table>
</body>
</html>

还有很多其他方法,还有更多支持此功能的库。最后,根据您的需求,您可以简单地创建CSV文件而不是xls。

最新更新