如果你需要一个“下载数据”按钮,它会自动启动一个电子表格(如 Excel),发现 fputcsv() 无法按预期工作,安装的 DBA 数据库引擎都没有创建可打开的电子表格,并且 XLS 生成组件太重了,那么这可能就是你需要的
<?php
// 要呈现的简单表格
$data = array(
array('col1','col2'),
array(1,2),
array(3,4)
);
// 假设内容(是 XML)是 XLS 本地格式
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"sheet.xls\";" );
// 构造骨架
$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = $dom->preserveSpaces = true; // 可选
$n = new DOMProcessingInstruction('mso-application', 'progid="Excel.Sheet"');
$dom->appendChild($n);
$workbook = $dom->appendChild(new DOMElement('Workbook'));
$workbook->setAttribute('xmlns','urn:schemas-microsoft-com:office:spreadsheet');
$workbook->setAttribute('xmlns:o','urn:schemas-microsoft-com:office:office');
$workbook->setAttribute('xmlns:x','urn:schemas-microsoft-com:office:excel');
$workbook->setAttribute('xmlns:ss','xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet');
$workbook->setAttribute('xmlns:html','http://www.w3.org/TR/REC-html40');
$styles = $workbook->appendChild(new DOMElement('Styles'));
$style = $styles->appendChild(new DOMElement('Style'));
$style->setAttribute('ss:ID','Default');
$worksheet = $workbook->appendChild(new DOMElement('Worksheet'));
$worksheet->setAttribute('ss:Name','sheet1');
$xmltable = $worksheet->appendChild(new DOMElement('Table'));
// 使用数据填充
foreach ($data as $datarow) {
$xmlrow = $xmltable->appendChild(new DOMElement('Row'));
foreach ($datarow as $datacell) {
$xmlcell = $xmlrow->appendChild(new DOMElement('Cell'));
$xmldata = $xmlcell->appendChild(new DOMElement('Data', $datacell));
$xmldata->setAttribute('ss:Type', is_numeric($datacell) ? 'Number' : 'String');
}
}
// 显示并退出
echo $dom->saveXML();
?>