我很难弄清楚我哪里出错了。
在使用从 MySQL 查询中检索到的数据填充它之后,我正在尝试将 excel (xlsx) 文件导出到浏览器,然后在某些情况下对其进行编辑。
这是我目前的代码...
if (isset($_POST['export']))
{
$SQL = "SELECT * FROM calls WHERE status = 'O'";
$result = mysql_query($SQL);
$filename = "Open_Calls_(". date("Y-m-d") . ").xlsx";
header("Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8");
header("Content-disposition: attachment; filename=$filename");
header('Cache-Control: max-age=0');
$data_exp = PHPExcel_IOFactory::createReader('Excel2007');
$data_exp = $data_exp->load('../template/Helpdesk - Open Calls.xlsx');
$data_exp->setActiveSheetIndex(0)
->setTitle('Open Calls');
$rowN = 2;
while ($row = mysql_fetch_row($result))
{
$contact1 = $row['contact_no1'];
$contact1 = substr_replace($contact1, "-", 3, 0);
$contact1 = substr_replace($contact1, "-", 7, 0);
if($row['contact_no2'] != "")
{
$contact2 = $row['contact_no2'];
$contact2 = substr_replace($contact2, "-", 3, 0);
$contact2 = substr_replace($contact2, "-", 7, 0);
}
else
{
$contact2 = "";
}
$date1 = new DateTime($row['doc']);
$date2 = new DateTime(date("Y-m-d"));
$col = 'A';
$data_exp->getActiveSheet()
->setCellValue(A.$rowN, $row['ref_no'])
->setCellValue(B.$rowN, $row['ref_type'])
->setCellValue(C.$rowN, $row['dem_code'])
->setCellValue(D.$rowN, $row['contact_name'])
->setCellValue(E.$rowN, $contact1)
->setCellValue(F.$rowN, $contact2)
->setCellValue(G.$rowN, $row['query_main'])
->setCellValue(H.$rowN, $row['query_sub'])
->setCellValue(I.$rowN, $row['icn_product'])
->setCellValue(J.$rowN, $row['iv_no'])
->setCellValue(K.$rowN, $row['order_no'])
->setCellValue(L.$rowN, $row['section'])
->setCellValue(M.$rowN, $row['action'])
->setCellValue(N.$rowN, $row['logged'])
->setCellValue(O.$rowN, $row['doc'])
->setCellValue(P.$rowN, $row['toc'])
->setCellValue(Q.$rowN, datediff($date1, $date2));
$rowN++;
}
$objWriter = PHPExcel_IOFactory::createWriter($data_exp, 'Excel2007');
ob_end_clean();
$objWriter->save('php://output');
exit;
}
所以我设法让文件输出为 excel2007 格式,但查询结果字段显示为空白......例如。->setCellValue(A.$rowN, $row['ref_no']) 返回一个空白。更具体地说, $row['ref_no'] 返回一个空白。事实上,所有这些。
但是,如果我要导出查询,因为它来自 foreach 循环中的查询,而根本不处理数据,那么 Excel 文件将被完美地填充。例如...
$rowN = 2;
while ($row = mysql_fetch_row($result))
{
$col = 'A';
foreach($row as $cell)
{
$data_exp->getActiveSheet()->setCellValue($col.$rowN,$cell);
$col++;
}
$rowN++;
}
这是为什么?
有人可以让我知道我哪里出错了。有什么我想念的吗?为什么不能单独调用查询结果字段?
我对php很陌生,更不用说phpexcel了,如果我输入了错误的标题或者我的格式错误,我会很感激有人告诉我。