将标头添加到导出的Excel文件

时间:2015-04-14 12:29:55

标签: php export-to-excel

我正在使用PHPExcel将数据库查询的结果导出到Excel,例如:

SELECT * FROM members WHERE BranchID=12345

虽然我可以导出行内容,但我(当然)也希望拥有列名。

以下代码可以导出数据:

<?php
session_start();
require_once'PHPExcel.php';
$branchID=$_SESSION['ITEM'];
$SQL = "SELECT * FROM members WHERE BranchID='$branchID' ORDER BY Type";
// Execute the database query
$result =sqlsrv_query($dbhandle, $SQL, array(), array( "Scrollable" => 'static'));

// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();

$objPHPExcel->getProperties()->setCreator("Donor tracking System")
                             ->setLastModifiedBy("DTS")
                             ->setTitle("All members")
                             ->setSubject("Office 2007 XLSX Test Document")
                             ->setDescription("All Members, generated using PHP classes.")
                             ->setKeywords("office 2007 openxml php")
                             ->setCategory("Test result file");

// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;

while($row = sqlsrv_fetch_array($result)){
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['Name']);

    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount,date_format( $row['dateOfreg'],"d-m-Y"));
    // Increment the Excel row counter
    $rowCount++;
} 
$objPHPExcel->getActiveSheet()->setTitle('All Members');

// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="allmembers.xls"');
header('Cache-Control: max-age=0');

// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter =  PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('php://output');

exit;
?>

如何在Excel文件的列中添加标题?

1 个答案:

答案 0 :(得分:0)

在开始编写从SQL服务器获取的行之前,只有一个包含每个列标题的数组并将其写入您的文件是否有意义?

编写标题,递增计数器变量,然后写入剩余的行。