How to set cell/column value dynamically using PHPExcel library?
I am fetching result set from MySQL database and I want to write data in excel format using PHPExcel
I don't have much experience working with php but from a logic standpoint this is what I would do.
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);
}
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++;
}