我们的应用程序需要导出到Excel工作表,其中包含多个选项卡(Excel工作表)。对于这个Am使用[PHPExcel] [1],但它工作正常,但如何从mysql数据库动态插入数据。
以下是我的代码:
<?php
require_once 'PHPExcel.php';
require_once 'PHPExcel/IOFactory.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Create a first sheet, representing sales data
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Something');
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Name of Sheet 1');
// Create a new worksheet, after the default sheet
$objPHPExcel->createSheet();
// Add some data to the second sheet, resembling some different data types
$objPHPExcel->setActiveSheetIndex(1);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'More data');
// Rename 2nd sheet
$objPHPExcel->getActiveSheet()->setTitle('Second sheet');
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="name_of_file.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
它工作正常,Excel工作表正在生成,但如何从数据库中添加数据以及Excel工作表列名称与表列名称。代替“$ objPHPExcel-&gt; getActiveSheet() - &gt; setCellValue('A1','更多数据');”如何动态添加表数据?
答案 0 :(得分:0)
使用select
查询将数据从db分配到数组中,并使用fromArray
将数据填充到Excel中
$data=[];
$i=2;
$mx=mysqli_query($con,"SELECT * FROM table");
while($row=mysqli_fetch_array($mx))
{
//values from db..col A,col B,col C,col D
$data= array($row[0],$row[1],$row[2],$row[3]);
//row number
$ii="A".$i;
//insert data from db to excel
$objPHPExcel->getActiveSheet()->fromArray($data, ' ', $ii);
$i++;
}