2012-07-10 26 views
13

PHPExcel kullanarak varolan bir .xls dosyasına yeni bir satır nasıl ekleyebilirim?PHPExcel ile yeni bir satır ekleme?

Halihazırda var olan satır sayısını hesaplamam mı gerekiyor?

Eğer öyleyse, bunu bir excel dosyası için nasıl yapabilirim? Öyle gibi satır sayısını elde edebilirsiniz

$objPHPExcel = PHPExcel_IOFactory::load("foo.xlsx"); 
$objWorksheet = $objPHPExcel->getActiveSheet(); 

:

cevap

28

Bu kurulumu varsayarsak

$num_rows = $objPHPExcel->getActiveSheet()->getHighestRow();

Bunu takiben, aşağıdaki ifadeyi kullanarak satır ekleme içine bakabilirsiniz:

$objWorksheet->insertNewRowBefore($num_rows + 1, 1);

Bu, $num_rows'dan önce 1 yeni satır ekler.

+0

$ objReader nasıl tanımlanır? – Novak

+0

Kod bölümünüzü takip ettim ve doğru sonucu almadım. Bir göz atabilir misiniz: http://stackoverflow.com/questions/32312743/phpexcel-how-to-use-insertnewrowbefore-function-correctly –

5

Yukarıdaki örnek yalnızca boş bir satır ekler. Aşağıdaki örnek, bir formdan gelen verileri ekler.

<?php 

     require_once '../inc/phpexcel/Classes/PHPExcel.php'; 
     require_once '../inc/phpexcel/Classes/PHPExcel/IOFactory.php'; 
     $objPHPExcel = PHPExcel_IOFactory::load("myExcelFile.xlsx"); 
     $objWorksheet = $objPHPExcel->getActiveSheet(); 

     //add the new row 
     $num_rows = $objPHPExcel->getActiveSheet()->getHighestRow(); 
     $objWorksheet->insertNewRowBefore($num_rows + 1, 1); 
     $name = isset($_POST['name']) ? $_POST['name'] : ''; 
     if($submit){ 
    //SAVING THE NEW ROW - on the last position in the table 
     $objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$name); 
     } 

     //display the table 
     echo '<table>'."\n"; 
     echo '<thead> 
     <tr> 
      <th>Company Name</th> 
     </tr> 
     </thead>'."\n"; 
     echo '<tbody>'."\n"; 
     foreach ($objWorksheet->getRowIterator() as $row) { 
     echo '<tr>'."\n"; 
     $cellIterator = $row->getCellIterator(); 
     $cellIterator->setIterateOnlyExistingCells(false); 
     foreach ($cellIterator as $cell) { 
     echo '<td>'.$cell->getValue().'</td>'."\n"; 
     } 
     echo '</tr>'."\n"; 
     } 
     echo '</tbody>'."\n"; 
     echo '</table>'."\n"; 
     ?> 
+0

Kodunuzu takip ettim ve doğru sonucu almadım. Lütfen bir bakabilir misin? http://stackoverflow.com/questions/32312743/phpexcel-how-to-use-insertnewrowbefore-function-correctly –