php PHPExcel如何动态设置单元格值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2584954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:01:19  来源:igfitidea点击:

PHPExcel how to set cell value dynamically

phpexcel-2003export-to-excelphpexcel

提问by Asif

How to set cell/column value dynamically using PHPExcel library?

如何使用 PHPExcel 库动态设置单元格/列值?

I am fetching result set from MySQL database and I want to write data in excel format using PHPExcel library. Looking at example

我正在从 MySQL 数据库中获取结果集,我想使用 PHPExcel 库以 excel 格式写入数据。看例子

$objPHPExcel->getActiveSheet()->setCellValue('A1', 'cell value here');

indicates that we have to hard code cell/column reference As 'A1', then it writes to cell/column A1. How I can increment cell/column and/or row reference based on rows and corresponding column values from result set?

表示我们必须将单元格/列引用硬编码为“A1”,然后写入单元格/列 A1。如何根据结果集中的行和相应的列值增加单元格/列和/或行引用?

Please guide.

请指导。

回答by Ivo Sabev

I asume you have connected to your database already.

我假设您已经连接到您的数据库。

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

回答by Jon

I don't have much experience working with php but from a logic standpoint this is what I would do.

我没有太多使用 php 的经验,但从逻辑的角度来看,这就是我要做的。

  1. Loop through your result set from MySQL
  2. In Excel you should already know what A,B,C should be because those are the columns and you know how many columns you are returning.
  3. The row number can just be incremented with each time through the loop.
  1. 循环遍历 MySQL 的结果集
  2. 在 Excel 中,您应该已经知道 A、B、C 应该是什么,因为这些是列,并且您知道要返回多少列。
  3. 每次循环时,行号都可以递增。

Below is some pseudocode illustrating this technique:

下面是一些说明这种技术的伪代码:

    for (int i = 0; i < MySQLResults.count; i++){
         $objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name); 
        // Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
         $objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
         $objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
    }