我有一个脚本,可以在excel文件的行中输入表单数据。每次发送表单时,新数据都会附加到同一个excel文件中。
问题是新数据附加了两行。因此,每行之间插入一个空行。
这是代码。 $ data包含$ _POST数据。
function generateExcel($data) {
$filename = dirname(__FILE__).'/myexcelfile.xlsx';
// this is shortened
$columns = array(
'fieldname1' => 'Column 1',
'fieldname2' => 'Column 2',
);
// check if file exist
if(file_exists($filename)) {
// load existing excel file
$objPHPExcel = PHPExcel_IOFactory::load($filename);
} else {
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->insertNewRowBefore(1, 1);
// Set column names
$columnIndex = 0;
foreach($columns as $columnName) {
$objWorksheet->setCellValueByColumnAndRow($columnIndex, 1, $columnName);
$columnIndex++;
}
}
// get sheet and highest row
$objWorksheet = $objPHPExcel->getActiveSheet();
$numberOfRows = $objPHPExcel->getActiveSheet()->getHighestRow();
// Insert a new row after highest row
$objWorksheet->insertNewRowBefore($numberOfRows + 1, 1);
// Get the highest row again (should be one more since last time)
// $numberOfRows2 = $objPHPExcel->getActiveSheet()->getHighestRow();
// Insert data for each column
$columnIndex = 0;
foreach($columns as $fieldName => $columnName) {
$fieldValue = $data[$fieldName];
$objWorksheet->setCellValueByColumnAndRow($columnIndex, $numberOfRows + 1, $fieldValue);
$columnIndex++;
}
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($filename);
}
这是我用的: https://stackoverflow.com/a/12417477
答案 0 :(得分:0)
我只是猜测,我们可以试试吗
$objWorksheet->setCellValueByColumnAndRow($columnIndex,"",$columnName);
而不是
$objWorksheet->setCellValueByColumnAndRow($columnIndex, 1, $columnName);