只有您加載到PHPExcel對象中的內容纔會被放入您的新文件中。
的createWriter不是編輯文件並保留表,它只是寫你傳遞什麼你給它的文件名的新副本。在這種情況下,它將覆蓋該文件,因爲它與您剛剛打開的文件相同。所以,你必須謹慎地抓住整個工作簿,然後改變你想要的(從整個工作表)。之後,將所有內容寫入文件中並添加新的更改。
下面的代碼應該幫助您保留其他工作表。要僅編輯特定工作表,只需將要編輯的工作表名稱放置在$ editable_worksheets數組中。我對這些評論非常具有描述性,所以希望他們能夠一步一步地闡明這是如何完成的。
// Load your PHPExcel class
require_once 'classes/PHPExcel/Classes/PHPExcel.php';
// Set variables for file location and type to make code more portable and
// less memory intensive
$file = '/tmp/ac.xlsx';
$file_type = 'Excel2007';
// Open file for reading
$objReader = PHPExcel_IOFactory::createReader($file_type);
// Take all exisiting worksheets in open file and place their names into an array
$worksheet_names = $objReader->listWorksheetNames($file);
// Array of worksheet names that should be editable
$editable_worksheets = array('activity', 'store');
// You will need to load ALL worksheets if you intend on saving to the same
// file name, so we will pass setLoadSheetsOnly() the array of worksheet names
// we just created.
$objReader->setLoadSheetsOnly($worksheet_names);
// Load the file
$objPHPExcel = $objReader->load($file);
// Loop through each worksheet in $worksheet_names array
foreach($worksheet_names as $worksheet_name) {
// Only edit the worksheets with names we've allowed in
// the $editable_worksheets array
if(in_array($worksheet_name, $editable_worksheets)) {
// Take each sheet, one at a time, and set it as the active sheet
$objPHPExcel->setActiveSheetIndexByName($worksheet_name);
// Grab the sheet you just made active
$sheet = $objPHPExcel->getActiveSheet();
// Grab the highest row from the current active sheet
$max_row = $sheet->getHighestRow();
// Set the value of column "A" in the last row to the text "Data"
$sheet->setCellValue("A" . $max_row, "Data");
}
// Foreach loop will repeat until all sheets in the workbook have been looped
// through
}
// Unset variables to free up memory
unset($worksheet_names, $worksheet_name, $sheet, $max_row);
// Prepare to write a new file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $file_type);
// Tell excel not to precalculate any formulas
$objWriter->setPreCalculateFormulas(false);
// Save the file
$objWriter->save($file);
// This must be called before unsetting to prevent memory leaks
$objPHPExcel->disconnectWorksheets();
// Again, unset variables to free up memory
unset($file, $file_type, $objReader, $objPHPExcel);
馬克您好,感謝您的建議..我面臨着同樣的probleam ......你已經在你的解決方案的最後一行寫道:「你需要到iPod所有四個工作表」那應該怎麼做? – Denish
如果可能,請給我提供代碼...因爲這對我來說非常緊迫....預先感謝很多:)) – Denish