gpt4 book ai didi

php - 如何使用 phpexcel 获取带有 mysql 数据的列名?

转载 作者:行者123 更新时间:2023-11-29 01:20:46 24 4
gpt4 key购买 nike

我正在使用 phpexcel 库将 mysql 数据导出到 excel 文件。该代码工作正常。但是创建的 excel 文件没有列名。我也想去取。有没有内置的方法?我需要什么调整来制作我的代码?这是我当前的工作代码:

<?php

require_once 'PHPExcel/classes/PHPExcel.php';

$objPHPExcel = new PHPExcel();

$objPHPExcel->setActiveSheetIndex(0);

$rowcount = 1;

while($row = mysqli_fetch_array($rs))
{
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $row['id']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $row['title']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $row['date']);
$rowcount++;
}

$filename = "backup-" . date("h.i.s.d-m-Y") . ".xls";
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=" . $filename);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

$objWriter->save('php://output');

?>

最佳答案

使用 mysqli_fetch_fields 获取字段名称。

我已经编辑了您的代码并在代码中添加了列名。它可能对您有所帮助。

<?php

require_once 'PHPExcel/classes/PHPExcel.php';

$objPHPExcel = new PHPExcel();

$objPHPExcel->setActiveSheetIndex(0);

$rowcount = 1;

$fieldinfo=mysqli_fetch_fields($rs);

foreach ($fieldinfo as $val)
{
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $val->id);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $val->title);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $val->date);
}

$rowcount = 2;

while($row = mysqli_fetch_array($rs))
{
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $row['id']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $row['title']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $row['date']);
$rowcount++;
}

$filename = "backup-" . date("h.i.s.d-m-Y") . ".xls";
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=" . $filename);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

$objWriter->save('php://output');

?>

关于php - 如何使用 phpexcel 获取带有 mysql 数据的列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32623152/

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