我有一个脚本,可以在 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);
}