最快速的是将数组呈现到 Excel 2007 并在桌面上安装 Google Drive App 以访问数据。Spreadsheets API 无法创建文档,需要使用 Docs API 来创建;目前 PHP 的 API 包装器不支持这两个端点 - 像这样我也可以修改文件。及时努力:1h。
更新:当我用 Excel2007 渲染 XLSX 时,转换失败。当我用 MS-Excel 和“另存为”打开同一个文件时,我什至可以通过 Drive API 转换它。
解压缩文件并进行比较时,我注意到了一些事情:
a) MS-Excel 使用值 '0/1' 而不是 'false/true'
b) 目录“xl/worksheets/_rels”被删除(可能没用?)。
c) XML 的行尾从 UNIX 转换为 DOS。
d) MS-Excel 将所有空单元格添加到 XML - PHPExcel 没有写出。
e)关系ID似乎发生了变化......代码中有一些+3计算?
问题是,生成的文件格式与 Drive API 的 XML 解析器不匹配。
我仍然不确定生成的文件格式有什么问题,但是用 MS-Excel 本地创建的 XML 文件修补呈现的 XLSX 文件使其工作:
/* how-to patch the generated XLSX: */
$zip = new ZipArchive();
$zip->open($xlsx_path);
$zip->extractTo($export_dir.'temp');
$zip->close();
$this->deleteDir($export_dir.'temp/xl/worksheets/_rels');
$files =array(
'_rels/.rels',
'docProps/app.xml',
'docProps/core.xml',
'xl/workbook.xml',
'xl/_rels/workbook.xml.rels',
'xl/theme/theme1.xml'
);
foreach($files as $file){
copy($export_dir.'template/'.$file, $export_dir.'temp/'.$file);
}
unlink($xlsx_path);
if($zip->open($xlsx_path, ZIPARCHIVE::CREATE)) {
$source = str_replace('\\', '/', realpath($export_dir.'temp'));
if(is_dir($source) === true) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) ){continue;}
$file = realpath($file);
if(is_dir($file) === true){$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));}
else if(is_file($file) === true){
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if(is_file($source) === true) {
$zip->addFromString(basename($source), file_get_contents($source));
}
$zip->close();
}
单元格格式不太合适 - 但转换和预览工作正常。
甚至可以从修补中跳过一些 XML 文件,而另一些则使其中断。