我使用XLSXWriter
将PHP数组导出到Excel。
$data = array(
array('id' => 0, 'name' => 'John Doe'),
array('id' => 1, 'name' => 'Jane Doe'),
array('id' => 2, 'name' => 'Will Smith'),
);
$writer = new XLSXWriter();
$writer->writeSheet($data);
$writer->writeToFile('path/and/filename.xlsx');
它以excel输出:
0 | John Doe
1 | Jane Doe
2 | Will Smith
没关系,但我还需要我的数组键作为第一行:
id | name
2 | Will Smith
0 | John Doe
1 | Jane Doe
2 | Will Smith
所以我这样做了:
$headings = array_keys($data[0]);
array_unshift($data,$headings);
它有效,但有更好的方法吗?
答案 0 :(得分:1)
writeSheetRow
怎么样? $data = array(
array('id' => 0, 'name' => 'John Doe'),
array('id' => 1, 'name' => 'Jane Doe'),
array('id' => 2, 'name' => 'Will Smith'),
);
$writer = new XLSXWriter();
$writer->writeSheetRow('Sheet1',['id','name']);
$writer->writeSheetRow('Sheet1',end($data));
$writer->writeSheet($data);
$writer->writeToFile('path/and/filename.xlsx');
输出
id | name
2 | Will Smith
0 | John Doe
1 | Jane Doe
2 | Will Smith
先添加最后一行,然后将整个数组添加到文件中。 希望这有效。