I have a script that inputs form data on a row in an excel file. Each time the form is sent the new data is appended to the same excel file.
我有一个脚本,在excel文件中的行上输入表单数据。每次发送表单时,新数据都会附加到同一个excel文件中。
The problem is that the new data is appended by two rows. So a blank row is inserted between each row.
问题是新数据附加了两行。因此在每行之间插入一个空行。
Here is the code. $data contains the $_POST data.
这是代码。 $ 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);
}
This is what I used: https://*.com/a/12417477
这就是我使用的:https://*.com/a/12417477
1 个解决方案
#1
0
I just guess that, can we try this
我只是想,我们可以尝试一下吗
$objWorksheet->setCellValueByColumnAndRow($columnIndex,"",$columnName);
instead of
代替
$objWorksheet->setCellValueByColumnAndRow($columnIndex, 1, $columnName);
#1
0
I just guess that, can we try this
我只是想,我们可以尝试一下吗
$objWorksheet->setCellValueByColumnAndRow($columnIndex,"",$columnName);
instead of
代替
$objWorksheet->setCellValueByColumnAndRow($columnIndex, 1, $columnName);