<?php
require_once 'PHPExcel.php';
require_once 'PHPExcel/IOFactory.php';
//Update the multiple sheets in PHP excel
$report_file = 'Report_' . date('Y-m-d') . '.xlsx';
$report_file_exists = 0;
//If the file doesnot exist , create new otherwise append the data at last
if (!file_exists($report_file)) {
$objPHPExcel = new PHPExcel();
} else {
$report_file_exists = 1;
$objPHPExcel = PHPExcel_IOFactory::load($report_file);
}
$columns = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
//Sheet details
$sheet_details = array(
//1st sheet details
0 => array('sheet_title' => 'Products',
'sheet_heading' => array('Article_Number','Name'),
'sheet_data' => array('1234','Pen')
),
//2nd Sheet Details
1 => array('sheet_title' => 'Categories',
'sheet_heading' => array('Category Id','Name'),
'sheet_data' => array(123,'Accessories')
)
);
$sheet_count = 0;
$row = 1;
$column = 0;
while ($sheet_count <= count($sheet_details)) {
$objWorkSheet = '';
if ($report_file_exists == 0) {
if ($sheet_count > 0) {
$objWorkSheet = $objPHPExcel->createSheet($sheet_count);
} else {
$objWorkSheet = $objPHPExcel->getActiveSheet();
}
$row = 1;
$column = 0;
foreach ($sheet_details[$sheet_count]['sheet_heading'] as $head) {
$objWorkSheet->setCellValue($columns[$column] . $row, $head);
$column++;
}
} else {
$objPHPExcel->setActiveSheetIndex($sheet_count);
$objWorkSheet = $objPHPExcel->getActiveSheet($sheet_count);
}
$row = $objWorkSheet->getHighestRow() + 1; //row count
foreach ($sheet_details[$sheet_count]['sheet_data'] as $report_details) {
$column = 0;
foreach ($report_details as $data) {
$objWorkSheet->setCellValue($columns[$column] . $row, $data);
$column++;
}
$row++;
}
$objWorkSheet->setTitle($sheet_details[$sheet_count]['sheet_title']);
$sheet_count++;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($report_file);
?>
除非您想要在現有行之前插入新行,否則您無需擔心。 set cellValue()會在你指定的單元格中添加數據:如果一個單元格的值已經存在,它將被覆蓋;如果它不存在,那麼它將被創建。如果您需要知道最後一行的編號,請使用工作表的getHighestRow()方法或getHighestDataRow()方法 – 2013-05-13 06:31:01
我只是想在每次發佈數據時添加新行,並且我的excel場已放置在服務器上。意味着我不想丟失舊數據。新數據新行。 – rahularyansharma 2013-05-13 06:32:38
在這種情況下:加載文件,調用getHighestRow()獲取最後一行,將其添加到該值,然後將新數據寫入新行號 – 2013-05-13 06:33:39