gpt4 book ai didi

php - 如何使用 PHP 将 SQL 表导出为 excel 格式

转载 作者:行者123 更新时间:2023-11-29 06:02:51 25 4
gpt4 key购买 nike

所以我需要可以下载我的 SQL 表。现在我的 php 文件创建了一个 excel 文件并强制下载,但 excel 文件只有一个大数组,其中包含表的数据。

这是我的代码

$sql = mysql_query("SELECT * FROM table");

while ($row_user = mysql_fetch_assoc($sql))
{ $userinfo[] = $row_user;

print_r($row_user);

header("Content-Disposition: attachment; filename=\"papi.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$file = fopen("php://output","w");

foreach($userinfo as $data)
{
fputcsv($file,explode(',',$data),"\t");
}

fclose($file);
}

如有任何帮助,我们将不胜感激,在此先感谢您。

最佳答案

有几个 PHP 库可以帮助您在强制下载之前格式化输出的 excel 文件。我在使用 PHPExcel 方面有很好的经验.

使用 PHPExcel 不会改变从表中访问数据的方式,但会改变处理 MySQL 结果的方式:

//Collect result set
$data = array();
while ($row = mysql_fetch_assoc($sql)){ $data[] = $row; }

//initialize PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("AuthorName")->setTitle("DocumentTitle");

//Write Column Titles into first Row
$col = 'A';
foreach($data[0] as $key => $val){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($col.1, $key);
$col++;
}

//Write Data
for($i = 0; $i < count($data); $i++){
$col = 'A';
$row = 2 + $i;
foreach($data[$i] as $val){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($col.$row, $val);
$col++;
}
}

//Set Header
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="DataExport.xlsx"');
header('Cache-Control: max-age=0');

//Output Results
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
$objWriter->save('php://output');

这绝不是唯一的选择,但是,我发现这个库对于将数据导出到 XLSX 文件很有用,并且还有其他选项可以格式化它或根据需要添加生成报告的方程式。

关于php - 如何使用 PHP 将 SQL 表导出为 excel 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com