嘿我正在尝试将一个Sqlsrv数据库表导出到excel,当我没有导出datetime列时效果很好但是一旦我这样做我就会收到此错误: 致命错误:无法在第86行的C:\ xampp \ htdocs \ PhpExport \ src \ PHPExcel \ Cell \ DefaultValueBinder.php中使用DateTime类型的对象
$sql = "SELECT * FROM ComSec_meeting ORDER BY submission_date";
$ stmt = sqlsrv_query($ conn,$ sql);
try {
// Set value binder
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
$sheet = new PHPExcel();
// Set metadata
$sheet->getProperties()->setCreator('Mozes')
->setLastModifiedBy('Mozes')
->setTitle('Try')
->setKeywords('Try');
// Set default settings
$sheet->getDefaultStyle()->getAlignment()->setVertical(
PHPExcel_Style_Alignment::VERTICAL_TOP);
$sheet->getDefaultStyle()->getAlignment()->setHorizontal(
PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$sheet->getDefaultStyle()->getFont()->setName('Lucida Sans Unicode');
$sheet->getDefaultStyle()->getFont()->setSize(12);
// Get reference to active spreadsheet in workbook
$sheet->setActiveSheetIndex(0);
$activeSheet = $sheet->getActiveSheet();
// Set print options
$activeSheet->getPageSetup()->setOrientation(
PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE)
->setFitToWidth(1)
->setFitToHeight(0);
$activeSheet->getHeaderFooter()->setOddHeader('&C&B&16' .
$sheet->getProperties()->getTitle())
->setOddFooter('&CPage &P of &N');
// Populate with data
$row = sqlsrv_fetch_array($stmt);
$colHeaders = array_keys($row);
$col = 'A';
$rownum = 1;
// Set column headings
foreach ($colHeaders as $header) {
$activeSheet->setCellValue($col . $rownum, $header);
$activeSheet->getStyle($col . $rownum)->getFont()->setBold(true);
$col++;
}
// Populate individual cells with data
do {
$col = 'A';
$rownum++;
foreach ($row as $value) {
$activeSheet->setCellValue($col++ . $rownum, $value);
}
} while ($row = sqlsrv_fetch_array($stmt));
// Format individual columns
$activeSheet->getStyle('E2:E' . $rownum)->getNumberFormat() ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
$activeSheet->getStyle('F2:F' . $rownum)->getNumberFormat() ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
// Give spreadsheet a title
$activeSheet->setTitle('Try');![enter image description here][1]
// Generate Excel file and download
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="TryOut.xlsx"');
header('Cache-Control: max-age=0');
$writer = PHPExcel_IOFactory::createWriter($sheet, 'Excel2007');
$writer->save('php://output');
} catch (Exception $e) {
$error = $e->getMessage();
}
答案 0 :(得分:0)
在尝试之前,使用E
将数据库结果集中的日期值(您在列F
和PHPExcel_Shared_Date::PHPToExcel()
中设置的值)转换为MS Excel序列化日期时间值在单元格中设置该值
foreach ($row as $value) {
if ($value instanceof DateTime) {
// Convert DateTime values to MS Excel serialized timestamps
$value = PHPExcel_Shared_Date::PHPToExcel($value);
}
$activeSheet->setCellValue($col++ . $rownum, $value);
}