繁体   English   中英

动态 mysql -> excel 导出

[英]Dynamic mysql -> excel export

首先 - “正常”导出和使用 phpspreadsheet 编写 Excel 文件就像一个魅力。 我不知道如何以动态方式做到这一点。 “动态”是指不手动定义row1的标题,也不手动定义来自 mysql 的数据列。

我所做的(尝试):

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('test');

if ($result = $mysqli -> query($sql)) {
    $co = 'A';
    $ro = '1';
    while ($fieldinfo = $result -> fetch_field()) {
        // printf("$col.$row %s\n", $fieldinfo -> name);
        $sheet->setCellValue($co.$ro, $fieldinfo -> name);
        $$co = $fieldinfo -> name;
        $co++;
        }
    $result -> free_result();
}

这将创建一个 excel 文件,其中包含在 mysql 视图/语句中定义的所有字段名称。 挑战是将日期逐列放入而不通过代码创建它们。 我所做的是为每一列生成一个变量。 所以$A = firstname$B = name ,等等。

我的想法是通过类似“第一列是 'A' 然后我必须解决变量$A来解决这个变量。但动态调用变量在某种程度上不起作用

$sheet->setCellValue($co.$ro, $row[$cuco]);

$cuco (当前列)应该是$cuco = '$'.$A ,但是$cuco的值将是$A并且解析的变量$A应该是“firstname”,即

我所做的是向数据库中的每一列添加一条注释,该注释与我想要的该列的标题相对应。 附加查询将为您提供该数据,然后您可以使用这些数据填充标题行。

这是我使用 FWIW 的功能:

//
// Returns an array indexed by column names with the column comment,
// if any, as the value from the table name that is passed - columns
// that do not have a comment are not included in the returned array
//

public function get_column_comments($table) {

$ColsQ = $this->database->prepare('SHOW FULL COLUMNS FROM `' . $table . '`');
$ColsQ->execute();
$ColsD = $ColsQ->fetchAll(PDO::FETCH_ASSOC);

foreach ($ColsD as $col) {

    if (empty($col['Comment'])) {continue;}  // ignore columns without a comment

    $cols[$col['Field']] = $col['Comment'];
}

return $cols;

}  // end of get_column_comments function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM