Example #1
5
 /**
  * Insert a new column, updating all possible related data
  *
  * @param	int	$pBefore	Insert before this one
  * @param	int	$pNumCols	Number of columns to insert
  * @param	int	$pNumRows	Number of rows to insert
  * @throws	Exception
  */
 public function insertNewBefore($pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, PHPExcel_Worksheet $pSheet = null)
 {
     // Get a copy of the cell collection
     /*$aTemp = $pSheet->getCellCollection();
     		$aCellCollection = array();
     		foreach ($aTemp as $key => $value) {
     			$aCellCollection[$key] = clone $value;
     		}*/
     $aCellCollection = $pSheet->getCellCollection();
     // Get coordinates of $pBefore
     $beforeColumn = 'A';
     $beforeRow = 1;
     list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString($pBefore);
     // Clear cells if we are removing columns or rows
     $highestColumn = $pSheet->getHighestColumn();
     $highestRow = $pSheet->getHighestRow();
     // 1. Clear column strips if we are removing columns
     if ($pNumCols < 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols > 0) {
         for ($i = 1; $i <= $highestRow - 1; ++$i) {
             for ($j = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1 + $pNumCols; $j <= PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2; ++$j) {
                 $coordinate = PHPExcel_Cell::stringFromColumnIndex($j) . $i;
                 $pSheet->removeConditionalStyles($coordinate);
                 if ($pSheet->cellExists($coordinate)) {
                     $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL);
                     $pSheet->getCell($coordinate)->setXfIndex(0);
                 }
             }
         }
     }
     // 2. Clear row strips if we are removing rows
     if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) {
         for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) {
             for ($j = $beforeRow + $pNumRows; $j <= $beforeRow - 1; ++$j) {
                 $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . $j;
                 $pSheet->removeConditionalStyles($coordinate);
                 if ($pSheet->cellExists($coordinate)) {
                     $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL);
                     $pSheet->getCell($coordinate)->setXfIndex(0);
                 }
             }
         }
     }
     // Loop through cells, bottom-up, and change cell coordinates
     while ($cell = $pNumCols < 0 || $pNumRows < 0 ? array_shift($aCellCollection) : array_pop($aCellCollection)) {
         // New coordinates
         $newCoordinates = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1 + $pNumCols) . ($cell->getRow() + $pNumRows);
         // Should the cell be updated? Move value and cellXf index from one cell to another.
         if (PHPExcel_Cell::columnIndexFromString($cell->getColumn()) >= PHPExcel_Cell::columnIndexFromString($beforeColumn) && $cell->getRow() >= $beforeRow) {
             // Update cell styles
             $pSheet->getCell($newCoordinates)->setXfIndex($cell->getXfIndex());
             $cell->setXfIndex(0);
             // Insert this cell at its new location
             if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
                 // Formula should be adjusted
                 $pSheet->setCellValue($newCoordinates, $this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows));
             } else {
                 // Formula should not be adjusted
                 $pSheet->setCellValue($newCoordinates, $cell->getValue());
             }
             // Clear the original cell
             $pSheet->setCellValue($cell->getCoordinate(), '');
         }
     }
     // Duplicate styles for the newly inserted cells
     $highestColumn = $pSheet->getHighestColumn();
     $highestRow = $pSheet->getHighestRow();
     if ($pNumCols > 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 > 0) {
         for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
             // Style
             $coordinate = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2) . $i;
             if ($pSheet->cellExists($coordinate)) {
                 $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
                 $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? $pSheet->getConditionalStyles($coordinate) : false;
                 for ($j = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $j <= PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols; ++$j) {
                     $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
                     if ($conditionalStyles) {
                         $cloned = array();
                         foreach ($conditionalStyles as $conditionalStyle) {
                             $cloned[] = clone $conditionalStyle;
                         }
                         $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($j) . $i, $cloned);
                     }
                 }
             }
         }
     }
     if ($pNumRows > 0 && $beforeRow - 1 > 0) {
         for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) {
             // Style
             $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1);
             if ($pSheet->cellExists($coordinate)) {
                 $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
                 $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? $pSheet->getConditionalStyles($coordinate) : false;
                 for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) {
                     $pSheet->getCell(PHPExcel_Cell::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
                     if ($conditionalStyles) {
                         $cloned = array();
                         foreach ($conditionalStyles as $conditionalStyle) {
                             $cloned[] = clone $conditionalStyle;
                         }
                         $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($i) . $j, $cloned);
                     }
                 }
             }
         }
     }
     // Update worksheet: column dimensions
     $aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true);
     if (count($aColumnDimensions) > 0) {
         foreach ($aColumnDimensions as $objColumnDimension) {
             $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows);
             list($newReference) = PHPExcel_Cell::coordinateFromString($newReference);
             if ($objColumnDimension->getColumnIndex() != $newReference) {
                 $objColumnDimension->setColumnIndex($newReference);
             }
         }
         $pSheet->refreshColumnDimensions();
     }
     // Update worksheet: row dimensions
     $aRowDimensions = array_reverse($pSheet->getRowDimensions(), true);
     if (count($aRowDimensions) > 0) {
         foreach ($aRowDimensions as $objRowDimension) {
             $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows);
             list(, $newReference) = PHPExcel_Cell::coordinateFromString($newReference);
             if ($objRowDimension->getRowIndex() != $newReference) {
                 $objRowDimension->setRowIndex($newReference);
             }
         }
         $pSheet->refreshRowDimensions();
         $copyDimension = $pSheet->getRowDimension($beforeRow - 1);
         for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) {
             $newDimension = $pSheet->getRowDimension($i);
             $newDimension->setRowHeight($copyDimension->getRowHeight());
             $newDimension->setVisible($copyDimension->getVisible());
             $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
             $newDimension->setCollapsed($copyDimension->getCollapsed());
         }
     }
     // Update worksheet: breaks
     $aBreaks = array_reverse($pSheet->getBreaks(), true);
     foreach ($aBreaks as $key => $value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         if ($key != $newReference) {
             $pSheet->setBreak($newReference, $value);
             $pSheet->setBreak($key, PHPExcel_Worksheet::BREAK_NONE);
         }
     }
     // Update worksheet: hyperlinks
     $aHyperlinkCollection = array_reverse($pSheet->getHyperlinkCollection(), true);
     foreach ($aHyperlinkCollection as $key => $value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         if ($key != $newReference) {
             $pSheet->setHyperlink($newReference, $value);
             $pSheet->setHyperlink($key, null);
         }
     }
     // Update worksheet: data validations
     $aDataValidationCollection = array_reverse($pSheet->getDataValidationCollection(), true);
     foreach ($aDataValidationCollection as $key => $value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         if ($key != $newReference) {
             $pSheet->setDataValidation($newReference, $value);
             $pSheet->setDataValidation($key, null);
         }
     }
     // Update worksheet: merge cells
     $aMergeCells = $pSheet->getMergeCells();
     $aNewMergeCells = array();
     // the new array of all merge cells
     foreach ($aMergeCells as $key => &$value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         $aNewMergeCells[$newReference] = $newReference;
     }
     $pSheet->setMergeCells($aNewMergeCells);
     // replace the merge cells array
     // Update worksheet: protected cells
     $aProtectedCells = array_reverse($pSheet->getProtectedCells(), true);
     foreach ($aProtectedCells as $key => $value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         if ($key != $newReference) {
             $pSheet->protectCells($newReference, $value, true);
             $pSheet->unprotectCells($key);
         }
     }
     // Update worksheet: autofilter
     if ($pSheet->getAutoFilter() != '') {
         $pSheet->setAutoFilter($this->updateCellReference($pSheet->getAutoFilter(), $pBefore, $pNumCols, $pNumRows));
     }
     // Update worksheet: freeze pane
     if ($pSheet->getFreezePane() != '') {
         $pSheet->freezePane($this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows));
     }
     // Page setup
     if ($pSheet->getPageSetup()->isPrintAreaSet()) {
         $pSheet->getPageSetup()->setPrintArea($this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows));
     }
     // Update worksheet: drawings
     $aDrawings = $pSheet->getDrawingCollection();
     foreach ($aDrawings as $objDrawing) {
         $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows);
         if ($objDrawing->getCoordinates() != $newReference) {
             $objDrawing->setCoordinates($newReference);
         }
     }
     // Update workbook: named ranges
     if (count($pSheet->getParent()->getNamedRanges()) > 0) {
         foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) {
             if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) {
                 $namedRange->setRange($this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows));
             }
         }
     }
     // Garbage collect
     $pSheet->garbageCollect();
 }
/**
 * 行を完全コピーする
 *
 * http://blog.kotemaru.org/old/2012/04/06.html より
 * @param PHPExcel_Worksheet $sheet
 * @param int $srcRow
 * @param int $dstRow
 * @param int $height
 * @param int $width
 * @throws PHPExcel_Exception
 */
function copyRows(PHPExcel_Worksheet $sheet, $srcRow, $dstRow, $height, $width)
{
    for ($row = 0; $row < $height; $row++) {
        // セルの書式と値の複製
        for ($col = 0; $col < $width; $col++) {
            $cell = $sheet->getCellByColumnAndRow($col, $srcRow + $row);
            $style = $sheet->getStyleByColumnAndRow($col, $srcRow + $row);
            $dstCell = PHPExcel_Cell::stringFromColumnIndex($col) . (string) ($dstRow + $row);
            $sheet->setCellValue($dstCell, $cell->getValue());
            $sheet->duplicateStyle($style, $dstCell);
        }
        // 行の高さ複製。
        $h = $sheet->getRowDimension($srcRow + $row)->getRowHeight();
        $sheet->getRowDimension($dstRow + $row)->setRowHeight($h);
    }
    // セル結合の複製
    // - $mergeCell="AB12:AC15" 複製範囲の物だけ行を加算して復元。
    // - $merge="AB16:AC19"
    foreach ($sheet->getMergeCells() as $mergeCell) {
        $mc = explode(":", $mergeCell);
        $col_s = preg_replace("/[0-9]*/", "", $mc[0]);
        $col_e = preg_replace("/[0-9]*/", "", $mc[1]);
        $row_s = (int) preg_replace("/[A-Z]*/", "", $mc[0]) - $srcRow;
        $row_e = (int) preg_replace("/[A-Z]*/", "", $mc[1]) - $srcRow;
        // 複製先の行範囲なら。
        if (0 <= $row_s && $row_s < $height) {
            $merge = $col_s . (string) ($dstRow + $row_s) . ":" . $col_e . (string) ($dstRow + $row_e);
            $sheet->mergeCells($merge);
        }
    }
}
Example #3
0
 /**
  * Store the MERGEDCELLS records for all ranges of merged cells
  */
 private function _writeMergedCells()
 {
     $mergeCells = $this->_phpSheet->getMergeCells();
     $countMergeCells = count($mergeCells);
     if ($countMergeCells == 0) {
         return;
     }
     // maximum allowed number of merged cells per record
     $maxCountMergeCellsPerRecord = 1027;
     // record identifier
     $record = 0xe5;
     // counter for total number of merged cells treated so far by the writer
     $i = 0;
     // counter for number of merged cells written in record currently being written
     $j = 0;
     // initialize record data
     $recordData = '';
     // loop through the merged cells
     foreach ($mergeCells as $mergeCell) {
         ++$i;
         ++$j;
         // extract the row and column indexes
         $range = PHPExcel_Cell::splitRange($mergeCell);
         list($first, $last) = $range[0];
         list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($first);
         list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($last);
         $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, PHPExcel_Cell::columnIndexFromString($firstColumn) - 1, PHPExcel_Cell::columnIndexFromString($lastColumn) - 1);
         // flush record if we have reached limit for number of merged cells, or reached final merged cell
         if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) {
             $recordData = pack('v', $j) . $recordData;
             $length = strlen($recordData);
             $header = pack('vv', $record, $length);
             $this->_append($header . $recordData);
             // initialize for next record, if any
             $recordData = '';
             $j = 0;
         }
     }
 }
Example #4
0
 /**
  * Write MergeCells
  *
  * @param	PHPExcel_Shared_XMLWriter			$objWriter		XML Writer
  * @param	PHPExcel_Worksheet					$pSheet			Worksheet
  * @throws	Exception
  */
 private function _writeMergeCells(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
 {
     if (count($pSheet->getMergeCells()) > 0) {
         // mergeCells
         $objWriter->startElement('mergeCells');
         // Loop mergeCells
         foreach ($pSheet->getMergeCells() as $mergeCell) {
             // mergeCell
             $objWriter->startElement('mergeCell');
             $objWriter->writeAttribute('ref', $mergeCell);
             $objWriter->endElement();
         }
         $objWriter->endElement();
     }
 }
Example #5
0
 /**
  * Update merged cells when inserting/deleting rows/columns
  *
  * @param   PHPExcel_Worksheet  $pSheet             The worksheet that we're editing
  * @param   string              $pBefore            Insert/Delete before this cell address (e.g. 'A1')
  * @param   integer             $beforeColumnIndex  Index number of the column we're inserting/deleting before
  * @param   integer             $pNumCols           Number of columns to insert/delete (negative values indicate deletion)
  * @param   integer             $beforeRow          Number of the row we're inserting/deleting before
  * @param   integer             $pNumRows           Number of rows to insert/delete (negative values indicate deletion)
  */
 protected function _adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)
 {
     $aMergeCells = $pSheet->getMergeCells();
     $aNewMergeCells = array();
     // the new array of all merge cells
     foreach ($aMergeCells as $key => &$value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         $aNewMergeCells[$newReference] = $newReference;
     }
     $pSheet->setMergeCells($aNewMergeCells);
     // replace the merge cells array
 }
Example #6
0
    /**
     * Insert a new column, updating all possible related data
     *
     * @param 	int	$pBefore	Insert before this one
     * @param 	int	$pNumCols	Number of columns to insert
     * @param 	int	$pNumRows	Number of rows to insert
     * @throws 	Exception
     */
    public function insertNewBefore($pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, PHPExcel_Worksheet $pSheet = null) {
		// Get a copy of the cell collection
		/*$aTemp = $pSheet->getCellCollection();
		$aCellCollection = array();
		foreach ($aTemp as $key => $value) {
			$aCellCollection[$key] = clone $value;
		}*/
		$aCellCollection = $pSheet->getCellCollection();

    	// Get coordinates of $pBefore
    	$beforeColumn 	= 'A';
    	$beforeRow		= 1;
    	list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString( $pBefore );


		// Remove cell styles?
		$highestColumn 	= $pSheet->getHighestColumn();
		$highestRow 	= $pSheet->getHighestRow();

		if ($pNumCols < 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols > 0) {
			for ($i = 1; $i <= $highestRow - 1; $i++) {

				$pSheet->duplicateStyle(
					new PHPExcel_Style(),
					(PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1 + $pNumCols ) . $i) . ':' . (PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 ) . $i)
				);

			}
		}

		if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) {
			for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; $i++) {

				$pSheet->duplicateStyle(
					new PHPExcel_Style(),
					(PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow + $pNumRows)) . ':' . (PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1))
				);

			}
		}


   		// Loop trough cells, bottom-up, and change cell coordinates
		while ( ($cell = ($pNumCols < 0 || $pNumRows < 0) ? array_shift($aCellCollection) : array_pop($aCellCollection)) ) {
			// New coordinates
			$newCoordinates = PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1 + $pNumCols ) . ($cell->getRow() + $pNumRows);

			// Should the cell be updated?
			if (
					(PHPExcel_Cell::columnIndexFromString( $cell->getColumn() ) >= PHPExcel_Cell::columnIndexFromString($beforeColumn)) &&
				 	($cell->getRow() >= $beforeRow)
				 ) {

				// Update cell styles
				$pSheet->duplicateStyle( $pSheet->getStyle($cell->getCoordinate()), $newCoordinates . ':' . $newCoordinates );
				$pSheet->duplicateStyle( $pSheet->getDefaultStyle(), $cell->getCoordinate() . ':' . $cell->getCoordinate() );

				// Insert this cell at its new location
				if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
					// Formula should be adjusted
					$pSheet->setCellValue(
						  $newCoordinates
						, $this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows)
					);
				} else {
					// Formula should not be adjusted
					$pSheet->setCellValue($newCoordinates, $cell->getValue());
				}

				// Clear the original cell
				$pSheet->setCellValue($cell->getCoordinate(), '');
			}
		}


		// Duplicate styles for the newly inserted cells
		$highestColumn 	= $pSheet->getHighestColumn();
		$highestRow 	= $pSheet->getHighestRow();

		if ($pNumCols > 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 > 0) {
			for ($i = $beforeRow; $i <= $highestRow - 1; $i++) {

				// Style
				$pSheet->duplicateStyle(
					$pSheet->getStyle(
						(PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 ) . $i)
					),
					($beforeColumn . $i) . ':' . (PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols ) . $i)
				);

			}
		}

		if ($pNumRows > 0 && $beforeRow - 1 > 0) {
			for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; $i++) {

				// Style
				$pSheet->duplicateStyle(
					$pSheet->getStyle(
						(PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1))
					),
					(PHPExcel_Cell::stringFromColumnIndex($i) . $beforeRow) . ':' . (PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1 + $pNumRows))
				);

			}
		}


		// Update worksheet: column dimensions
		$aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true);
		foreach ($aColumnDimensions as $objColumnDimension) {
			$newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows);
			list($newReference) = PHPExcel_Cell::coordinateFromString($newReference);
			if ($objColumnDimension->getColumnIndex() != $newReference) {
				$objColumnDimension->setColumnIndex($newReference);
			}
		}
		$pSheet->refreshColumnDimensions();


		// Update worksheet: row dimensions
		$aRowDimensions = array_reverse($pSheet->getRowDimensions(), true);
		foreach ($aRowDimensions as $objRowDimension) {
			$newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows);
			list(, $newReference) = PHPExcel_Cell::coordinateFromString($newReference);
			if ($objRowDimension->getRowIndex() != $newReference) {
				$objRowDimension->setRowIndex($newReference);
			}
		}
		$pSheet->refreshRowDimensions();

		$copyDimension = $pSheet->getRowDimension($beforeRow - 1);
		for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; $i++) {
			$newDimension = $pSheet->getRowDimension($i);
			$newDimension->setRowHeight($copyDimension->getRowHeight());
			$newDimension->setVisible($copyDimension->getVisible());
			$newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
			$newDimension->setCollapsed($copyDimension->getCollapsed());
		}


		// Update worksheet: breaks
		$aBreaks = array_reverse($pSheet->getBreaks(), true);
		foreach ($aBreaks as $key => $value) {
			$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
			if ($key != $newReference) {
				$pSheet->setBreak( $newReference, $value );
				$pSheet->setBreak( $key, PHPExcel_Worksheet::BREAK_NONE );
			}
		}


		// Update worksheet: merge cells
		$aMergeCells = array_reverse($pSheet->getMergeCells(), true);
		foreach ($aMergeCells as $key => $value) {
			$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
			if ($key != $newReference) {
				$pSheet->mergeCells( $newReference );
				$pSheet->unmergeCells( $key );
			}
		}


		// Update worksheet: protected cells
		$aProtectedCells = array_reverse($pSheet->getProtectedCells(), true);
		foreach ($aProtectedCells as $key => $value) {
			$newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
			if ($key != $newReference) {
				$pSheet->protectCells( $newReference, $value, true );
				$pSheet->unprotectCells( $key );
			}
		}


		// Update worksheet: autofilter
		if ($pSheet->getAutoFilter() != '') {
			$pSheet->setAutoFilter( $this->updateCellReference($pSheet->getAutoFilter(), $pBefore, $pNumCols, $pNumRows) );
		}


		// Update worksheet: freeze pane
		if ($pSheet->getFreezePane() != '') {
			$pSheet->setFreezePane( $this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows) );
		}


		// Page setup
		if ($pSheet->getPageSetup()->isPrintAreaSet()) {
			$pSheet->getPageSetup()->setPrintArea( $this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows) );
		}


		// Update worksheet: drawings
		$aDrawings = $pSheet->getDrawingCollection();
		foreach ($aDrawings as $objDrawing) {
			$newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows);
			if ($objDrawing->getCoordinates() != $newReference) {
				$objDrawing->setCoordinates($newReference);
			}
		}


		// Update workbook: named ranges
		if (count($pSheet->getParent()->getNamedRanges()) > 0) {
			foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) {
				if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) {
					$namedRange->setRange(
						$this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows)
					);
				}
			}
		}


		// Garbage collect
		$pSheet->garbageCollect();
    }
Example #7
0
 /**
  * Write row to HTML file
  * 
  * @param	mixed				$pFileHandle	PHP filehandle
  * @param	PHPExcel_Worksheet 	$pSheet			PHPExcel_Worksheet
  * @param	array				$pValues		Array containing cells in a row
  * @param	int					$pRow			Row number
  * @throws	Exception
  */
 private function _writeRow($pFileHandle = null, PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0)
 {
     if (!is_null($pFileHandle) && is_array($pValues)) {
         // Write row start
         fwrite($pFileHandle, '        <tr class="row' . $pRow . '">' . "\r\n");
         // Write cells
         $colNum = 0;
         foreach ($pValues as $cell) {
             $cellData = '&nbsp;';
             $cssClass = 'column' . $colNum;
             $colSpan = 1;
             $rowSpan = 1;
             $writeCell = true;
             // Write cell
             // PHPExcel_Cell
             if ($cell instanceof PHPExcel_Cell) {
                 // Value
                 if ($cell->getValue() instanceof PHPExcel_RichText) {
                     // Loop trough rich text elements
                     $elements = $cell->getValue()->getRichTextElements();
                     foreach ($elements as $element) {
                         // Rich text start?
                         if ($element instanceof PHPExcel_RichText_Run) {
                             $cellData .= '<span style="' . str_replace("\r\n", '', $this->_createCSSStyleFont($element->getFont())) . '">';
                         }
                         $cellData .= $element->getText();
                         if ($element instanceof PHPExcel_RichText_Run) {
                             $cellData .= '</span>';
                         }
                     }
                 } else {
                     if ($this->_preCalculateFormulas) {
                         $cellData = PHPExcel_Style_NumberFormat::toFormattedString($cell->getCalculatedValue(), $pSheet->getstyle($cell->getCoordinate())->getNumberFormat()->getFormatCode());
                     } else {
                         $cellData = PHPExcel_Style_NumberFormat::ToFormattedString($cell->getValue(), $pSheet->getstyle($cell->getCoordinate())->getNumberFormat()->getFormatCode());
                     }
                 }
                 // Check value
                 if ($cellData == '') {
                     $cellData = '&nbsp;';
                 }
                 // Extend CSS class?
                 if (array_key_exists($cell->getCoordinate(), $pSheet->getStyles())) {
                     $cssClass .= ' style' . $pSheet->getStyle($cell->getCoordinate())->getHashCode();
                 }
             } else {
                 $cell = new PHPExcel_Cell(PHPExcel_Cell::stringFromColumnIndex($colNum), $pRow + 1, '', null, null);
             }
             // Hyperlink?
             if ($cell->hasHyperlink() && !$cell->getHyperlink()->isInternal()) {
                 $cellData = '<a href="' . $cell->getHyperlink()->getUrl() . '" title="' . $cell->getHyperlink()->getTooltip() . '">' . $cellData . '</a>';
             }
             // Column/rowspan
             foreach ($pSheet->getMergeCells() as $cells) {
                 if ($cell->isInRange($cells)) {
                     list($first, ) = PHPExcel_Cell::splitRange($cells);
                     if ($first == $cell->getCoordinate()) {
                         list($colSpan, $rowSpan) = PHPExcel_Cell::rangeDimension($cells);
                     } else {
                         $writeCell = false;
                     }
                     break;
                 }
             }
             // Write
             if ($writeCell) {
                 // Column start
                 fwrite($pFileHandle, '          <td');
                 fwrite($pFileHandle, ' class="' . $cssClass . '"');
                 if ($colSpan > 1) {
                     fwrite($pFileHandle, ' colspan="' . $colSpan . '"');
                 }
                 if ($rowSpan > 1) {
                     fwrite($pFileHandle, ' rowspan="' . $rowSpan . '"');
                 }
                 fwrite($pFileHandle, '>');
                 // Image?
                 $this->_writeImageInCell($pFileHandle, $pSheet, $cell->getCoordinate());
                 // Cell data
                 fwrite($pFileHandle, $cellData);
                 // Column end
                 fwrite($pFileHandle, '</td>' . "\r\n");
             }
             // Next column
             $colNum++;
         }
         // Write row end
         fwrite($pFileHandle, '        </tr>' . "\r\n");
     } else {
         throw new Exception("Invalid parameters passed.");
     }
 }
 /**
  * Insert a new column, updating all possible related data
  *
  * @param	int	$pBefore	Insert before this one
  * @param	int	$pNumCols	Number of columns to insert
  * @param	int	$pNumRows	Number of rows to insert
  * @throws	Exception
  */
 public function insertNewBefore($pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, PHPExcel_Worksheet $pSheet = null)
 {
     $aCellCollection = $pSheet->getCellCollection();
     // Get coordinates of $pBefore
     $beforeColumn = 'A';
     $beforeRow = 1;
     list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString($pBefore);
     // Clear cells if we are removing columns or rows
     $highestColumn = $pSheet->getHighestColumn();
     $highestRow = $pSheet->getHighestRow();
     // 1. Clear column strips if we are removing columns
     if ($pNumCols < 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols > 0) {
         for ($i = 1; $i <= $highestRow - 1; ++$i) {
             for ($j = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1 + $pNumCols; $j <= PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2; ++$j) {
                 $coordinate = PHPExcel_Cell::stringFromColumnIndex($j) . $i;
                 $pSheet->removeConditionalStyles($coordinate);
                 if ($pSheet->cellExists($coordinate)) {
                     $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL);
                     $pSheet->getCell($coordinate)->setXfIndex(0);
                 }
             }
         }
     }
     // 2. Clear row strips if we are removing rows
     if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) {
         for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) {
             for ($j = $beforeRow + $pNumRows; $j <= $beforeRow - 1; ++$j) {
                 $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . $j;
                 $pSheet->removeConditionalStyles($coordinate);
                 if ($pSheet->cellExists($coordinate)) {
                     $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL);
                     $pSheet->getCell($coordinate)->setXfIndex(0);
                 }
             }
         }
     }
     // Loop through cells, bottom-up, and change cell coordinates
     while ($cellID = $pNumCols < 0 || $pNumRows < 0 ? array_shift($aCellCollection) : array_pop($aCellCollection)) {
         $cell = $pSheet->getCell($cellID);
         // New coordinates
         $newCoordinates = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1 + $pNumCols) . ($cell->getRow() + $pNumRows);
         // Should the cell be updated? Move value and cellXf index from one cell to another.
         if (PHPExcel_Cell::columnIndexFromString($cell->getColumn()) >= PHPExcel_Cell::columnIndexFromString($beforeColumn) && $cell->getRow() >= $beforeRow) {
             // Update cell styles
             $pSheet->getCell($newCoordinates)->setXfIndex($cell->getXfIndex());
             $cell->setXfIndex(0);
             // Insert this cell at its new location
             if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
                 // Formula should be adjusted
                 $pSheet->getCell($newCoordinates)->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle()));
             } else {
                 // Formula should not be adjusted
                 $pSheet->getCell($newCoordinates)->setValue($cell->getValue());
             }
             // Clear the original cell
             $pSheet->getCell($cell->getCoordinate())->setValue('');
         } else {
             /*	We don't need to update styles for rows/columns before our insertion position,
             			but we do still need to adjust any formulae	in those cells					*/
             if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
                 // Formula should be adjusted
                 $cell->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle()));
             }
         }
     }
     // Duplicate styles for the newly inserted cells
     $highestColumn = $pSheet->getHighestColumn();
     $highestRow = $pSheet->getHighestRow();
     if ($pNumCols > 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 > 0) {
         for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
             // Style
             $coordinate = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2) . $i;
             if ($pSheet->cellExists($coordinate)) {
                 $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
                 $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? $pSheet->getConditionalStyles($coordinate) : false;
                 for ($j = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $j <= PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols; ++$j) {
                     $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
                     if ($conditionalStyles) {
                         $cloned = array();
                         foreach ($conditionalStyles as $conditionalStyle) {
                             $cloned[] = clone $conditionalStyle;
                         }
                         $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($j) . $i, $cloned);
                     }
                 }
             }
         }
     }
     if ($pNumRows > 0 && $beforeRow - 1 > 0) {
         for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) {
             // Style
             $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1);
             if ($pSheet->cellExists($coordinate)) {
                 $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
                 $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? $pSheet->getConditionalStyles($coordinate) : false;
                 for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) {
                     $pSheet->getCell(PHPExcel_Cell::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
                     if ($conditionalStyles) {
                         $cloned = array();
                         foreach ($conditionalStyles as $conditionalStyle) {
                             $cloned[] = clone $conditionalStyle;
                         }
                         $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($i) . $j, $cloned);
                     }
                 }
             }
         }
     }
     // Update worksheet: column dimensions
     $aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true);
     if (!empty($aColumnDimensions)) {
         foreach ($aColumnDimensions as $objColumnDimension) {
             $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows);
             list($newReference) = PHPExcel_Cell::coordinateFromString($newReference);
             if ($objColumnDimension->getColumnIndex() != $newReference) {
                 $objColumnDimension->setColumnIndex($newReference);
             }
         }
         $pSheet->refreshColumnDimensions();
     }
     // Update worksheet: row dimensions
     $aRowDimensions = array_reverse($pSheet->getRowDimensions(), true);
     if (!empty($aRowDimensions)) {
         foreach ($aRowDimensions as $objRowDimension) {
             $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows);
             list(, $newReference) = PHPExcel_Cell::coordinateFromString($newReference);
             if ($objRowDimension->getRowIndex() != $newReference) {
                 $objRowDimension->setRowIndex($newReference);
             }
         }
         $pSheet->refreshRowDimensions();
         $copyDimension = $pSheet->getRowDimension($beforeRow - 1);
         for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) {
             $newDimension = $pSheet->getRowDimension($i);
             $newDimension->setRowHeight($copyDimension->getRowHeight());
             $newDimension->setVisible($copyDimension->getVisible());
             $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
             $newDimension->setCollapsed($copyDimension->getCollapsed());
         }
     }
     // Update worksheet: breaks
     $aBreaks = array_reverse($pSheet->getBreaks(), true);
     foreach ($aBreaks as $key => $value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         if ($key != $newReference) {
             $pSheet->setBreak($newReference, $value);
             $pSheet->setBreak($key, PHPExcel_Worksheet::BREAK_NONE);
         }
     }
     // Update worksheet: comments
     $aComments = $pSheet->getComments();
     $aNewComments = array();
     // the new array of all comments
     foreach ($aComments as $key => &$value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         $aNewComments[$newReference] = $value;
     }
     $pSheet->setComments($aNewComments);
     // replace the comments array
     // Update worksheet: hyperlinks
     $aHyperlinkCollection = array_reverse($pSheet->getHyperlinkCollection(), true);
     foreach ($aHyperlinkCollection as $key => $value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         if ($key != $newReference) {
             $pSheet->setHyperlink($newReference, $value);
             $pSheet->setHyperlink($key, null);
         }
     }
     // Update worksheet: data validations
     $aDataValidationCollection = array_reverse($pSheet->getDataValidationCollection(), true);
     foreach ($aDataValidationCollection as $key => $value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         if ($key != $newReference) {
             $pSheet->setDataValidation($newReference, $value);
             $pSheet->setDataValidation($key, null);
         }
     }
     // Update worksheet: merge cells
     $aMergeCells = $pSheet->getMergeCells();
     $aNewMergeCells = array();
     // the new array of all merge cells
     foreach ($aMergeCells as $key => &$value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         $aNewMergeCells[$newReference] = $newReference;
     }
     $pSheet->setMergeCells($aNewMergeCells);
     // replace the merge cells array
     // Update worksheet: protected cells
     $aProtectedCells = array_reverse($pSheet->getProtectedCells(), true);
     foreach ($aProtectedCells as $key => $value) {
         $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
         if ($key != $newReference) {
             $pSheet->protectCells($newReference, $value, true);
             $pSheet->unprotectCells($key);
         }
     }
     // Update worksheet: autofilter
     $autoFilter = $pSheet->getAutoFilter();
     $autoFilterRange = $autoFilter->getRange();
     if (!empty($autoFilterRange)) {
         if ($pNumCols != 0) {
             $autoFilterColumns = array_keys($autoFilter->getColumns());
             if (count($autoFilterColumns) > 0) {
                 list($column, $row) = sscanf($pBefore, '%[A-Z]%d');
                 $columnIndex = PHPExcel_Cell::columnIndexFromString($column);
                 list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($autoFilterRange);
                 if ($columnIndex <= $rangeEnd[0]) {
                     if ($pNumCols < 0) {
                         //	If we're actually deleting any columns that fall within the autofilter range,
                         //		then we delete any rules for those columns
                         $deleteColumn = $columnIndex + $pNumCols - 1;
                         $deleteCount = abs($pNumCols);
                         for ($i = 1; $i <= $deleteCount; ++$i) {
                             if (in_array(PHPExcel_Cell::stringFromColumnIndex($deleteColumn), $autoFilterColumns)) {
                                 $autoFilter->clearColumn(PHPExcel_Cell::stringFromColumnIndex($deleteColumn));
                             }
                             ++$deleteColumn;
                         }
                     }
                     $startCol = $columnIndex > $rangeStart[0] ? $columnIndex : $rangeStart[0];
                     //	Shuffle columns in autofilter range
                     if ($pNumCols > 0) {
                         //	For insert, we shuffle from end to beginning to avoid overwriting
                         $startColID = PHPExcel_Cell::stringFromColumnIndex($startCol - 1);
                         $toColID = PHPExcel_Cell::stringFromColumnIndex($startCol + $pNumCols - 1);
                         $endColID = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]);
                         $startColRef = $startCol;
                         $endColRef = $rangeEnd[0];
                         $toColRef = $rangeEnd[0] + $pNumCols;
                         do {
                             $autoFilter->shiftColumn(PHPExcel_Cell::stringFromColumnIndex($endColRef - 1), PHPExcel_Cell::stringFromColumnIndex($toColRef - 1));
                             --$endColRef;
                             --$toColRef;
                         } while ($startColRef <= $endColRef);
                     } else {
                         //	For delete, we shuffle from beginning to end to avoid overwriting
                         $startColID = PHPExcel_Cell::stringFromColumnIndex($startCol - 1);
                         $toColID = PHPExcel_Cell::stringFromColumnIndex($startCol + $pNumCols - 1);
                         $endColID = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]);
                         do {
                             $autoFilter->shiftColumn($startColID, $toColID);
                             ++$startColID;
                             ++$toColID;
                         } while ($startColID != $endColID);
                     }
                 }
             }
         }
         $pSheet->setAutoFilter($this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows));
     }
     // Update worksheet: freeze pane
     if ($pSheet->getFreezePane() != '') {
         $pSheet->freezePane($this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows));
     }
     // Page setup
     if ($pSheet->getPageSetup()->isPrintAreaSet()) {
         $pSheet->getPageSetup()->setPrintArea($this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows));
     }
     // Update worksheet: drawings
     $aDrawings = $pSheet->getDrawingCollection();
     foreach ($aDrawings as $objDrawing) {
         $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows);
         if ($objDrawing->getCoordinates() != $newReference) {
             $objDrawing->setCoordinates($newReference);
         }
     }
     // Update workbook: named ranges
     if (count($pSheet->getParent()->getNamedRanges()) > 0) {
         foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) {
             if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) {
                 $namedRange->setRange($this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows));
             }
         }
     }
     // Garbage collect
     $pSheet->garbageCollect();
 }
Example #9
0
 /**
  * Функция преобразования листа Excel в таблицу MySQL, с учетом объединенных строк и столбцов. Значения берутся уже вычисленными
  *
  * @param PHPExcel_Worksheet $worksheet                - Лист Excel
  * @param string             $table_name               - Имя таблицы MySQL
  * @param int|array          $columns_names            - Строка или массив с именами столбцов таблицы MySQL (0 - имена типа column + n). Если указано больше столбцов, чем на листе Excel, будут использованы значения по умолчанию указанных типов столбцов. Если указано ложное значение (null, false, "", 0, -1...) столбец игнорируется
  * @param bool|int           $start_row_index          - Номер строки, с которой начинается обработка данных (например, если 1 строка шапка таблицы). Нумерация начинается с 1, как в Excel
  * @param bool|array         $condition_functions      - Массив функций с условиями добавления строки по значению столбца (столбец => функция)
  * @param bool|array         $transform_functions      - Массив функций для изменения значения столбца (столбец => функция)
  * @param bool|int           $unique_column_for_update - Номер столбца с уникальным значением для обновления таблицы. Работает если $columns_names - массив (название столбца берется из него по [$unique_column_for_update - 1])
  * @param bool|array         $table_types              - Типы столбцов таблицы (используется при создании таблицы), в SQL формате - "INT(11) NOT NULL". Если не указаны, то используется "TEXT NOT NULL"
  * @param bool|array         $table_keys               - Ключевые поля таблицы (тип => столбец)
  * @param string             $table_encoding           - Кодировка таблицы MySQL
  * @param string             $table_engine             - Тип таблицы MySQL
  *
  * @return bool - Флаг, удалось ли выполнить функцию в полном объеме
  */
 private function excel_to_mysql($worksheet, $table_name, $columns_names, $start_row_index, $condition_functions, $transform_functions, $unique_column_for_update, $table_types, $table_keys, $table_encoding, $table_engine)
 {
     // Проверяем соединение с MySQL
     if (!$this->mysql_connect->connect_error) {
         // Строка для названий столбцов таблицы MySQL
         $columns = array();
         // Количество столбцов на листе Excel
         $columns_count = \PHPExcel_Cell::columnIndexFromString($worksheet->getHighestColumn());
         // Если в качестве имен столбцов передан массив, то проверяем соответствие его длинны с количеством столбцов
         if ($columns_names) {
             if (is_array($columns_names)) {
                 $columns_names_count = count($columns_names);
                 if ($columns_names_count < $columns_count) {
                     return false;
                 } elseif ($columns_names_count > $columns_count) {
                     $columns_count = $columns_names_count;
                 }
             } else {
                 return false;
             }
         }
         // Если указаны типы столбцов
         if ($table_types) {
             if (is_array($table_types)) {
                 // Проверяем количество столбцов и типов
                 if (count($table_types) != count($columns_names)) {
                     return false;
                 }
             } else {
                 return false;
             }
         }
         $table_name = "`{$table_name}`";
         // Проверяем, что $columns_names - массив и $unique_column_for_update находиться в его пределах
         if ($unique_column_for_update) {
             $unique_column_for_update = is_array($columns_names) ? $unique_column_for_update <= count($columns_names) ? "`{$columns_names[$unique_column_for_update - 1]}`" : false : false;
         }
         // Перебираем столбцы листа Excel и генерируем строку с именами через запятую
         for ($column = 0; $column < $columns_count; $column++) {
             $column_name = is_array($columns_names) ? $columns_names[$column] : ($columns_names == 0 ? "column{$column}" : $worksheet->getCellByColumnAndRow($column, $columns_names)->getValue());
             $columns[] = $column_name ? "`{$column_name}`" : null;
         }
         $query_string = "DROP TABLE IF EXISTS {$table_name}";
         if (defined("EXCEL_MYSQL_DEBUG")) {
             if (EXCEL_MYSQL_DEBUG) {
                 var_dump($query_string);
             }
         }
         // Удаляем таблицу MySQL, если она существовала (если не указан столбец с уникальным значением для обновления)
         if ($unique_column_for_update ? true : $this->mysql_connect->query($query_string)) {
             $columns_types = $ignore_columns = array();
             // Обходим столбцы и присваиваем типы
             foreach ($columns as $index => $value) {
                 if ($value == null) {
                     $ignore_columns[] = $index;
                     unset($columns[$index]);
                 } else {
                     if ($table_types) {
                         $columns_types[] = "{$value} {$table_types[$index]}";
                     } else {
                         $columns_types[] = "{$value} TEXT NOT NULL";
                     }
                 }
             }
             // Если указаны ключевые поля, то создаем массив ключей
             if ($table_keys) {
                 $columns_keys = array();
                 foreach ($table_keys as $key => $value) {
                     $columns_keys[] = "{$value} (`{$key}`)";
                 }
                 $columns_keys_list = implode(", ", $columns_keys);
                 $columns_keys = ", {$columns_keys_list}";
             } else {
                 $columns_keys = null;
             }
             $columns_types_list = implode(", ", $columns_types);
             $query_string = "CREATE TABLE IF NOT EXISTS {$table_name} ({$columns_types_list}{$columns_keys}) COLLATE = '{$table_encoding}' ENGINE = {$table_engine}";
             if (defined("EXCEL_MYSQL_DEBUG")) {
                 if (EXCEL_MYSQL_DEBUG) {
                     var_dump($query_string);
                 }
             }
             // Создаем таблицу MySQL
             if ($this->mysql_connect->query($query_string)) {
                 // Коллекция значений уникального столбца для удаления несуществующих строк в файле импорта (используется при обновлении)
                 $id_list_in_import = array();
                 // Количество строк на листе Excel
                 $rows_count = $worksheet->getHighestRow();
                 // Получаем массив всех объединенных ячеек
                 $all_merged_cells = $worksheet->getMergeCells();
                 // Перебираем строки листа Excel
                 for ($row = $start_row_index ? $start_row_index : (is_array($columns_names) ? 1 : $columns_names + 1); $row <= $rows_count; $row++) {
                     // Строка со значениями всех столбцов в строке листа Excel
                     $values = array();
                     // Перебираем столбцы листа Excel
                     for ($column = 0; $column < $columns_count; $column++) {
                         if (in_array($column, $ignore_columns)) {
                             continue;
                         }
                         // Строка со значением объединенных ячеек листа Excel
                         $merged_value = null;
                         // Ячейка листа Excel
                         $cell = $worksheet->getCellByColumnAndRow($column, $row);
                         // Перебираем массив объединенных ячеек листа Excel
                         foreach ($all_merged_cells as $merged_cells) {
                             // Если текущая ячейка - объединенная,
                             if ($cell->isInRange($merged_cells)) {
                                 // то вычисляем значение первой объединенной ячейки, и используем её в качестве значения текущей ячейки
                                 $merged_value = explode(":", $merged_cells);
                                 $merged_value = $worksheet->getCell($merged_value[0])->getValue();
                                 break;
                             }
                         }
                         // Проверяем, что ячейка не объединенная: если нет, то берем ее значение, иначе значение первой объединенной ячейки
                         $value = strlen($merged_value) == 0 ? $cell->getValue() : $merged_value;
                         // Если задан массив функций с условиями
                         if ($condition_functions) {
                             if (isset($condition_functions[$columns_names[$column]])) {
                                 // Проверяем условие
                                 if (!$condition_functions[$columns_names[$column]]($value)) {
                                     break;
                                 }
                             }
                         }
                         $value = $transform_functions ? isset($transform_functions[$columns_names[$column]]) ? $transform_functions[$columns_names[$column]]($value) : $value : $value;
                         $values[] = "'{$this->mysql_connect->real_escape_string($value)}'";
                     }
                     // Если количество столбцов не равно количеству значений, значит строка не прошла проверку
                     if ($columns_count - count($ignore_columns) != count($values)) {
                         continue;
                     }
                     // Добавляем или проверяем обновлять ли значение
                     $add_to_table = $unique_column_for_update ? false : true;
                     // Если обновляем
                     if ($unique_column_for_update) {
                         // Объединяем массивы для простоты работы
                         $columns_values = array_combine($columns, $values);
                         // Сохраняем уникальное значение
                         $id_list_in_import[] = $columns_values[$unique_column_for_update];
                         // Создаем условие выборки
                         $where = " WHERE {$unique_column_for_update} = {$columns_values[$unique_column_for_update]}";
                         // Удаляем столбец выборки
                         unset($columns_values[$unique_column_for_update]);
                         $query_string = "SELECT COUNT(*) AS count FROM {$table_name}{$where}";
                         if (defined("EXCEL_MYSQL_DEBUG")) {
                             if (EXCEL_MYSQL_DEBUG) {
                                 var_dump($query_string);
                             }
                         }
                         // Проверяем есть ли запись в таблице
                         $count = $this->mysql_connect->query($query_string);
                         $count = $count->fetch_assoc();
                         // Если есть, то создаем запрос и обновляем
                         if (intval($count['count']) != 0) {
                             $set = array();
                             foreach ($columns_values as $column => $value) {
                                 $set[] = "{$column} = {$value}";
                             }
                             $set_list = implode(", ", $set);
                             $query_string = "UPDATE {$table_name} SET {$set_list}{$where}";
                             if (defined("EXCEL_MYSQL_DEBUG")) {
                                 if (EXCEL_MYSQL_DEBUG) {
                                     var_dump($query_string);
                                 }
                             }
                             if (!$this->mysql_connect->query($query_string)) {
                                 return false;
                             }
                         } else {
                             $add_to_table = true;
                         }
                     }
                     // Добавляем строку в таблицу MySQL
                     if ($add_to_table) {
                         $columns_list = implode(", ", $columns);
                         $values_list = implode(", ", $values);
                         $query_string = "INSERT INTO {$table_name} ({$columns_list}) VALUES ({$values_list})";
                         if (defined("EXCEL_MYSQL_DEBUG")) {
                             if (EXCEL_MYSQL_DEBUG) {
                                 var_dump($query_string);
                             }
                         }
                         if (!$this->mysql_connect->query($query_string)) {
                             return false;
                         }
                     }
                 }
                 if (!empty($id_list_in_import)) {
                     $id_list = implode(", ", $id_list_in_import);
                     $query_string = "DELETE FROM {$table_name} WHERE {$unique_column_for_update} NOT IN ({$id_list})";
                     if (defined("EXCEL_MYSQL_DEBUG")) {
                         if (EXCEL_MYSQL_DEBUG) {
                             var_dump($query_string);
                         }
                     }
                     $this->mysql_connect->query($query_string);
                 }
                 return true;
             }
         }
     }
     return false;
 }
Example #10
0
 /**
  * Generate row
  *
  * @param	PHPExcel_Worksheet 	$pSheet			PHPExcel_Worksheet
  * @param	array				$pValues		Array containing cells in a row
  * @param	int					$pRow			Row number
  * @return	string
  * @throws	Exception
  */
 private function _generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0)
 {
     if (is_array($pValues)) {
         // Construct HTML
         $html = '';
         // Sheet hashcode
         $sheetHash = $pSheet->getHashCode();
         // Write row start
         if (!$this->_useInlineCss) {
             $html .= '        <tr class="row' . $pRow . '">' . "\r\n";
         } else {
             $style = isset($this->_cssStyles['table.sheet' . $sheetHash . ' tr.row' . $pRow]) ? $this->_cssStyles['table.sheet' . $sheetHash . ' tr.row' . $pRow] : '';
             $html .= '        <tr style="' . $style . '">' . "\r\n";
         }
         // Write cells
         $colNum = 0;
         foreach ($pValues as $cell) {
             $cellData = '&nbsp;';
             $cssClass = '';
             if (!$this->_useInlineCss) {
                 $cssClass = 'column' . $colNum;
             } else {
                 $cssClass = isset($this->_cssStyles['table.sheet' . $sheetHash . ' td.column' . $colNum]) ? $this->_cssStyles['table.sheet' . $sheetHash . ' td.column' . $colNum] : '';
             }
             $colSpan = 1;
             $rowSpan = 1;
             $writeCell = true;
             // Write cell
             // PHPExcel_Cell
             if ($cell instanceof PHPExcel_Cell) {
                 // Value
                 if ($cell->getValue() instanceof PHPExcel_RichText) {
                     // Loop trough rich text elements
                     $elements = $cell->getValue()->getRichTextElements();
                     foreach ($elements as $element) {
                         // Rich text start?
                         if ($element instanceof PHPExcel_RichText_Run) {
                             $cellData .= '<span style="' . str_replace("\r\n", '', $this->_createCSSStyleFont($element->getFont())) . '">';
                             if ($element->getFont()->getSuperScript()) {
                                 $cellData .= '<sup>';
                             } else {
                                 if ($element->getFont()->getSubScript()) {
                                     $cellData .= '<sub>';
                                 }
                             }
                         }
                         // Convert UTF8 data to PCDATA
                         $cellText = $element->getText();
                         $cellData .= htmlspecialchars($cellText);
                         if ($element instanceof PHPExcel_RichText_Run) {
                             if ($element->getFont()->getSuperScript()) {
                                 $cellData .= '</sup>';
                             } else {
                                 if ($element->getFont()->getSubScript()) {
                                     $cellData .= '</sub>';
                                 }
                             }
                             $cellData .= '</span>';
                         }
                     }
                 } else {
                     if ($this->_preCalculateFormulas) {
                         $cellData = PHPExcel_Style_NumberFormat::toFormattedString($cell->getCalculatedValue(), $pSheet->getstyle($cell->getCoordinate())->getNumberFormat()->getFormatCode());
                     } else {
                         $cellData = PHPExcel_Style_NumberFormat::ToFormattedString($cell->getValue(), $pSheet->getstyle($cell->getCoordinate())->getNumberFormat()->getFormatCode());
                     }
                     // Convert UTF8 data to PCDATA
                     $cellData = htmlspecialchars($cellData);
                 }
                 // Check value
                 if ($cellData == '') {
                     $cellData = '&nbsp;';
                 }
                 // Extend CSS class?
                 if (array_key_exists($cell->getCoordinate(), $pSheet->getStyles())) {
                     if (!$this->_useInlineCss) {
                         $cssClass .= ' style' . $pSheet->getStyle($cell->getCoordinate())->getHashIndex();
                         $cssClass .= ' ' . $cell->getDataType();
                     } else {
                         $cssClass .= isset($this->_cssStyles['style' . $pSheet->getStyle($cell->getCoordinate())->getHashIndex()]) ? $this->_cssStyles['style' . $pSheet->getStyle($cell->getCoordinate())->getHashIndex()] : '';
                         // General horizontal alignment: Actual horizontal alignment depends on dataType
                         if ($pSheet->getStyle($cell->getCoordinate())->getAlignment()->getHorizontal() == PHPExcel_Style_Alignment::HORIZONTAL_GENERAL && isset($this->_cssStyles['.' . $cell->getDataType()])) {
                             if (preg_match('/text-align: [^;]*;/', $cssClass)) {
                                 $cssClass = preg_replace('/text-align: [^;]*;/', $this->_cssStyles['.' . $cell->getDataType()], $cssClass);
                             } else {
                                 $cssClass .= $this->_cssStyles['.' . $cell->getDataType()];
                             }
                         }
                     }
                 }
             } else {
                 $cell = new PHPExcel_Cell(PHPExcel_Cell::stringFromColumnIndex($colNum), $pRow + 1, '', null, null);
             }
             // Hyperlink?
             if ($cell->hasHyperlink() && !$cell->getHyperlink()->isInternal()) {
                 $cellData = '<a href="' . htmlspecialchars($cell->getHyperlink()->getUrl()) . '" title="' . htmlspecialchars($cell->getHyperlink()->getTooltip()) . '">' . $cellData . '</a>';
             }
             // Column/rowspan
             foreach ($pSheet->getMergeCells() as $cells) {
                 if ($cell->isInRange($cells)) {
                     list($first, ) = PHPExcel_Cell::splitRange($cells);
                     if ($first[0] == $cell->getCoordinate()) {
                         list($colSpan, $rowSpan) = PHPExcel_Cell::rangeDimension($cells);
                     } else {
                         $writeCell = false;
                     }
                     break;
                 }
             }
             // Write
             if ($writeCell) {
                 // Column start
                 $html .= '          <td';
                 if (!$this->_useInlineCss) {
                     $html .= ' class="' . $cssClass . '"';
                 } else {
                     //** Necessary redundant code for the sake of PHPExcel_Writer_PDF **
                     // We must explicitly write the width of the <td> element because TCPDF
                     // does not recognize e.g. <col style="width:42pt">;
                     $width = 0;
                     $columnIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1;
                     for ($i = $columnIndex; $i < $columnIndex + $colSpan; ++$i) {
                         if (isset($this->_columnWidths[$sheetHash][$i])) {
                             $width += $this->_columnWidths[$sheetHash][$i];
                         }
                     }
                     $cssClass .= 'width: ' . $width . 'pt; ';
                     //** end of redundant code **
                     $html .= ' style="' . $cssClass . '"';
                 }
                 if ($colSpan > 1) {
                     $html .= ' colspan="' . $colSpan . '"';
                 }
                 if ($rowSpan > 1) {
                     $html .= ' rowspan="' . $rowSpan . '"';
                 }
                 $html .= '>';
                 // Image?
                 $html .= $this->_writeImageTagInCell($pSheet, $cell->getCoordinate());
                 // Cell data
                 $html .= $cellData;
                 // Column end
                 $html .= '</td>' . "\r\n";
             }
             // Next column
             ++$colNum;
         }
         // Write row end
         $html .= '        </tr>' . "\r\n";
         // Return
         return $html;
     } else {
         throw new Exception("Invalid parameters passed.");
     }
 }
Example #11
-1
 /**
  * Generate row
  *
  * @param	PHPExcel_Worksheet 	$pSheet			PHPExcel_Worksheet
  * @param	array				$pValues		Array containing cells in a row
  * @param	int					$pRow			Row number
  * @return	string
  * @throws	Exception
  */
 private function _generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0)
 {
     if (is_array($pValues)) {
         // Construct HTML
         $html = '';
         // Sheet hashcode
         $sheetHash = $pSheet->getHashCode();
         // Write row start
         if (!$this->_useInlineCss) {
             $html .= '        <tr class="row' . $pRow . '">' . "\r\n";
         } else {
             $style = isset($this->_cssStyles['table.sheet' . $sheetHash . ' tr.row' . $pRow]) ? $this->_cssStyles['table.sheet' . $sheetHash . ' tr.row' . $pRow] : '';
             $html .= '        <tr style="' . $style . '">' . "\r\n";
         }
         // Write cells
         $colNum = 0;
         foreach ($pValues as $cell) {
             $cellData = '&nbsp;';
             $cssClass = '';
             if (!$this->_useInlineCss) {
                 $cssClass = 'column' . $colNum;
             } else {
                 $cssClass = isset($this->_cssStyles['table.sheet' . $sheetHash . ' td.column' . $colNum]) ? $this->_cssStyles['table.sheet' . $sheetHash . ' td.column' . $colNum] : '';
             }
             $colSpan = 1;
             $rowSpan = 1;
             $writeCell = true;
             // Write cell
             // PHPExcel_Cell
             if ($cell instanceof PHPExcel_Cell) {
                 // Value
                 if ($cell->getValue() instanceof PHPExcel_RichText) {
                     // Loop trough rich text elements
                     $elements = $cell->getValue()->getRichTextElements();
                     foreach ($elements as $element) {
                         // Rich text start?
                         if ($element instanceof PHPExcel_RichText_Run) {
                             $cellData .= '<span style="' . str_replace("\r\n", '', $this->_createCSSStyleFont($element->getFont())) . '">';
                             if ($element->getFont()->getSuperScript()) {
                                 $cellData .= '<sup>';
                             } else {
                                 if ($element->getFont()->getSubScript()) {
                                     $cellData .= '<sub>';
                                 }
                             }
                         }
                         // Convert UTF8 data to PCDATA
                         $cellText = $element->getText();
                         $cellData .= htmlspecialchars($cellText);
                         if ($element instanceof PHPExcel_RichText_Run) {
                             if ($element->getFont()->getSuperScript()) {
                                 $cellData .= '</sup>';
                             } else {
                                 if ($element->getFont()->getSubScript()) {
                                     $cellData .= '</sub>';
                                 }
                             }
                             $cellData .= '</span>';
                         }
                     }
                 } else {
                     if ($this->_preCalculateFormulas) {
                         $cellData = PHPExcel_Style_NumberFormat::toFormattedString($cell->getCalculatedValue(), $pSheet->getstyle($cell->getCoordinate())->getNumberFormat()->getFormatCode());
                     } else {
                         $cellData = PHPExcel_Style_NumberFormat::ToFormattedString($cell->getValue(), $pSheet->getstyle($cell->getCoordinate())->getNumberFormat()->getFormatCode());
                     }
                     // Convert UTF8 data to PCDATA
                     $cellData = htmlspecialchars($cellData);
                 }
                 // Check value
                 if ($cellData == '') {
                     $cellData = '&nbsp;';
                 }
                 // Extend CSS class?
                 if (array_key_exists($cell->getCoordinate(), $pSheet->getStyles())) {
                     if (!$this->_useInlineCss) {
                         $cssClass .= ' style' . $pSheet->getStyle($cell->getCoordinate())->getHashIndex();
                     } else {
                         $cssClass .= isset($this->_cssStyles['style' . $pSheet->getStyle($cell->getCoordinate())->getHashIndex()]) ? $this->_cssStyles['style' . $pSheet->getStyle($cell->getCoordinate())->getHashIndex()] : '';
                     }
                 }
             } else {
                 $cell = new PHPExcel_Cell(PHPExcel_Cell::stringFromColumnIndex($colNum), $pRow + 1, '', null, null);
             }
             // Hyperlink?
             if ($cell->hasHyperlink() && !$cell->getHyperlink()->isInternal()) {
                 $cellData = '<a href="' . htmlspecialchars($cell->getHyperlink()->getUrl()) . '" title="' . htmlspecialchars($cell->getHyperlink()->getTooltip()) . '">' . $cellData . '</a>';
             }
             // Column/rowspan
             foreach ($pSheet->getMergeCells() as $cells) {
                 if ($cell->isInRange($cells)) {
                     list($first, ) = PHPExcel_Cell::splitRange($cells);
                     if ($first == $cell->getCoordinate()) {
                         list($colSpan, $rowSpan) = PHPExcel_Cell::rangeDimension($cells);
                     } else {
                         $writeCell = false;
                     }
                     break;
                 }
             }
             // Write
             if ($writeCell) {
                 // Column start
                 $html .= '          <td';
                 if (!$this->_useInlineCss) {
                     $html .= ' class="' . $cssClass . '"';
                 } else {
                     $html .= ' style="' . $cssClass . '"';
                 }
                 if ($colSpan > 1) {
                     $html .= ' colspan="' . $colSpan . '"';
                 }
                 if ($rowSpan > 1) {
                     $html .= ' rowspan="' . $rowSpan . '"';
                 }
                 $html .= '>';
                 // Image?
                 $html .= $this->_writeImageTagInCell($pSheet, $cell->getCoordinate());
                 // Cell data
                 if ($this->_useInlineCss) {
                     $html .= '<span style="' . $cssClass . '">';
                 }
                 $html .= $cellData;
                 if ($this->_useInlineCss) {
                     $html .= '</span>';
                 }
                 // Column end
                 $html .= '</td>' . "\r\n";
             }
             // Next column
             ++$colNum;
         }
         // Write row end
         $html .= '        </tr>' . "\r\n";
         // Return
         return $html;
     } else {
         throw new Exception("Invalid parameters passed.");
     }
 }