From 28f0dcfc0827f8738b9b7fb928fd094fc291117c Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Sat, 12 Apr 2014 00:55:51 +0200 Subject: [PATCH 0001/1332] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 031e9fe71..777e3a38d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel 4 Wrapper for PHPExcel v0.3.4 +## Laravel 4 Wrapper for PHPExcel v0.4.0 - DEV [![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![Latest Unstable Version](https://poser.pugx.org/maatwebsite/excel/v/unstable.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) [![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) From 55f996aa08ff897eb4202c2b338b9aa8a9725b15 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 12 Apr 2014 13:26:34 +0000 Subject: [PATCH 0002/1332] Structural changes with seperate readers/writers/parsers. Start of rewriting create file from array --- composer.json | 2 +- src/Maatwebsite/Excel/Classes/PHPExcel.php | 120 ++ src/Maatwebsite/Excel/Excel.php | 1401 +---------------- .../Excel/ExcelServiceProvider.php | 29 +- src/config/config.php | 56 + 5 files changed, 255 insertions(+), 1353 deletions(-) create mode 100644 src/Maatwebsite/Excel/Classes/PHPExcel.php diff --git a/composer.json b/composer.json index 629f90af0..b183de9ee 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ }, "autoload": { "classmap": [ - "src/Maatwebsite/Excel/Readers" + "src/Maatwebsite/Excel" ], "psr-0": { "Maatwebsite\\Excel": "src/" diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php new file mode 100644 index 000000000..5cee8c7f5 --- /dev/null +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -0,0 +1,120 @@ +_workSheetCollection = array(); + $this->_workSheetCollection[] = new LaravelExcelWorksheet($this); + + } + + /** + * Set default properties + */ + public function setDefaultProperties($custom) + { + $properties = $this->getProperties(); + + // Get fillable properties + foreach($this->allowedProperties as $prop) + { + // Get the method + $method = 'set' . ucfirst($prop); + + // get the value + $value = in_array($prop, array_keys($custom)) ? $custom[$prop] : \Config::get('excel::properties.' . $prop, NULL); + + // set the propertie + $properties->{$method}($value); + } + } + + /** + * Get active sheet + * + * @return PHPExcel_Worksheet + */ + public function getActiveSheet() + { + return $this->_workSheetCollection[$this->_activeSheetIndex]; + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index db26de148..ec83da3de 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -12,6 +12,7 @@ use Maatwebsite\Excel\Readers\HTML_reader; use Illuminate\Config\Repository as Config; use Illuminate\Filesystem\Filesystem as File; +use Maatwebsite\Excel\Writers\LaravelExcelWriter; /** * Laravel wrapper for PHPEXcel @@ -24,125 +25,54 @@ class Excel { - /** - * PHP Excel object - * @var [type] - */ - public $excel; - - /** - * Writer object - * @var [type] - */ - protected $object; /** - * Current sheet number - * @var integer - */ - public $i = 0; - - /** - * File title + * Excel object * @var [type] */ - public $title; + public $excel; /** - * File extension + * Html reader * @var [type] */ - public $ext; + protected $htmlReader; /** - * Format + * Config repository * @var [type] */ - public $format; + protected $config; /** - * Delimtier + * View factory * @var [type] */ - public $delimiter; + protected $viewFactory; /** - * Calculate [true/false] + * File system * @var [type] */ - public $calculate; - - /** - * Limit data - * @var boolean - */ - public $limit = false; + protected $fileSystem; /** - * Slug seperator + * Default CSV delimiter * @var string */ - public $seperator = '-'; + protected $delimiter = ','; /** - * Loaded view - * @var [type] - */ - protected $view; - - /** - * View rendered + * Calculate formulas * @var boolean */ - protected $viewRendered = false; - - /** - * View data - * @var array - */ - protected $data = array(); - - /** - * View merge Data - * @var [type] - */ - protected $mergeData; - - /** - * Sheet title - * @var [type] - */ - protected $sheetTitle; - - /** - * Default sheet orientation - * @var string - */ - protected $orientation = 'landscape'; + protected $calculate = true; /** * Ignore empty cells * @var boolean */ - protected $ignoreEmpty = false; - - /** - * File is parsed - * @var boolean - */ - protected $isParsed = false; - - /** - * Use first row as array indices - * @var boolean - */ - protected $firstRowAsLabel = false; - - /** - * Format dates - * @var boolean - */ - protected $formatDates = true; + protected $ignoreEmpty = true; /** * Default date format @@ -151,1302 +81,73 @@ class Excel protected $dateFormat = 'Y-m-d'; /** - * Use carbon to format dates - * @var boolean - */ - protected $useCarbon = false; - - /** - * Default carbon method + * Sheet heading to indices space replacer * @var string */ - protected $carbonMethod = 'toDateTimeString'; + protected $seperator = '_'; + /** - * - * Constructor - * - * Init the parent, init PHPExcel and set the defaults - * + * Construct Excel + * @param PHPExcel $excel [description] + * @param HTML_reader $htmlReader [description] + * @param Config $config [description] + * @param View $view [description] + * @param File $file [description] */ - - public function __construct(PHPExcel $excel, HTML_reader $htmlReader, Config $config, View $view, File $file) + public function __construct(PHPExcel $excel, LaravelExcelWriter $writer, HTML_reader $htmlReader, Config $config, View $view, File $file) { - // Set dependencies + // Set Excel dependencies $this->excel = $excel; + $this->writer = $writer; $this->htmlReader = $htmlReader; + + // Set Laravel classes $this->config = $config; $this->viewFactory = $view; $this->fileSystem = $file; // Set defaults - $this->delimiter = $this->config->get('excel::delimiter', $this->delimiter); - $this->calculate = $this->config->get('excel::calculate', $this->calculate); - $this->ignoreEmpty = $this->config->get('excel::ignoreEmpty', $this->ignoreEmpty); - $this->dateFormat = $this->config->get('excel::date_format', $this->dateFormat); - $this->seperator = $this->config->get('excel::seperator', $this->seperator); + $this->_setDefaults(); // Reset $this->reset(); } /** - * - * Create a new excel file, with default values and a file title. - * - * @param str $title The file title - * @return $this - * + * Create a new file + * @param [type] $title [description] + * @return [type] [description] */ public function create($title) { - // Reset - $this->reset(); - - // Set file title - $this->title = $title; - // Remove the default worksheet - $this->excel->disconnectWorksheets(); + // Set the default properties + $this->excel->setDefaultProperties(array( + 'title' => $title + )); - // Set properties - $this->excel->getProperties() - ->setCreator($this->config->get('excel::creator')) - ->setLastModifiedBy($this->config->get('excel::creator')) - ->setTitle($this->title); + // Inject our excel object + $this->writer->injectExcel($this->excel); - return $this; + // Set the title + $this->writer->setTitle($title); + // Return the writer object + return $this->writer; } /** - * - * Load an existing file - * - * @param str $file The file we want to load - * @param bool $firstRowAsLabel Do we want to interpret de first row as labels? - * @return $this - * + * Set defaults */ - public function load($file, $firstRowAsLabel = false, $inputEncoding = 'UTF-8') + protected function _setDefaults() { - // Reset - $this->reset(); - // Set defaults - $this->file = $file; - $this->ext = $this->fileSystem->extension($this->file); - $this->title = basename($this->file, '.' . $this->ext); - $this->firstRowAsLabel = $firstRowAsLabel; - - // Identify the format - $this->format = PHPExcel_IOFactory::identify($this->file); - - // Init the reader - $this->reader = PHPExcel_IOFactory::createReader($this->format); - - if ($this->format === 'CSV') - $this->reader->setInputEncoding($inputEncoding); - - // Load the file - $this->excel = $this->reader->load($this->file); - - // Return itself - return $this; - } - - /** - * Reload the reader - * @return [type] [description] - */ - public function reload() - { - $this->excel = $this->reader->load($this->file); - return $this; - } - - /** - * Set the date format - * @param str $format The date format - */ - public function setDateFormat($format) - { - $this->dateFormat = $format; - return $this; - } - - /** - * Enable/disable date formating - * @param bool $boolean True/false - */ - public function formatDates($boolean) - { - $this->formatDates = $boolean; - return $this; - } - - /** - * Use carbon to format dates - * @param boolean $method [description] - * @return [type] [description] - */ - public function useCarbon($method = false) - { - $this->useCarbon = true; - - if($method) - { - $this->carbonMethod = $method; - } - - return $this; - } - - /** - * - * Load a HTML string - * - * @param string $string - * @return static - * - */ - public function loadHTML($string) - { - $this->reader = $this->htmlReader; - return $this->reader->load($string, true); - } - - /** - * - * Load a View and convert to HTML - * - * @param string $view - * @param array $data - * @param array $mergeData - * @return static - * - */ - public function loadView($view, $data = array(), $mergeData = array()) - { - // Reset - $this->reset(); - - $this->view = $view; - $this->data = $data; - $this->mergeData = $mergeData; - return $this; - } - - /** - * - * Set the delimiter for CSV - * - * @param str $delimiter The delimiter we want to use - * @return $this - * - */ - public function setDelimiter($delimiter) - { - $this->delimiter = $delimiter; - $this->reader->setDelimiter($delimiter); - $this->reload(); - return $this; - } - /** - * - * Set the delimiter for CSV - * - * @param str $delimiter The delimiter we want to use - * @return $this - * - */ - public function setEnclosure($enclosure = '') - { - $this->reader->setEnclosure($enclosure); - $this->reload(); - return $this; - } - - /** - * - * Set the delimiter for CSV - * - * @param str $delimiter The delimiter we want to use - * @return $this - * - */ - public function setLineEnding($lineEnding = "\r\n") - { - $this->reader->setLineEnding($lineEnding); - $this->reload(); - return $this; - } - - /** - * - * Set the file title - * - * @param str $title The file title - * @return $this - * - */ - public function setTitle($title) - { - $this->title = $title; - return $this; - } - - /** - * - * Set default calculate - * - * @param bool $do Calculate yes or no - * @return $this - * - */ - public function calculate($do = true) - { - $this->calculate = $do; - return $this; - } - - /** - * - * Set the limit - * - * @param int $amount The amount we want to return - * @param int $start The position we wil start on - * @return $this - * - */ - public function limit($amount, $start = 0) - { - // Set the limit - $this->limit = array($amount, $start); - return $this; - } - - /** - * - * Select columns from the array - * - * @param array $keys The columns we want to select - * @return $this - * - */ - public function select($keys = array()) - { - // Parse the file - $this->parseFile(); - - // Check if we have selected keys - if(!empty($keys)) - { - - // Get the already parsed file - $rows = $this->parsed; - - // Reset the original parsed file to an empty array - $this->parsed = array(); - - $i = 0; - - // Loop through the rows - foreach($rows as $row) - { - - // Loop throug the cells and keys - foreach($row as $key => $cell) - { - - // Check if the key is in the array - if(in_array($key, $keys)) - { - // Add to the new parsed array - $this->parsed[$i][$key] = $cell; - } - } - $i++; - } - - } - - return $this; - } - - /** - * - * Parse the file to an array. - * - * @return array $this->parsed The parsed array - * - */ - public function toArray() - { - // Parse the file - $this->parseFile(); - - return (array) $this->parsed; - } - - /** - * - * Parse the file to an object. - * - * @return obj $this->parsed The parsed object - * - */ - public function toObject() - { - // Parse the file - $this->parseFile(); - return (object) json_decode(json_encode($this->parsed)); - } - - /** - * - * Dump the parsed file to a readable array - * - * @return array $this->parsed The parsed array - * - */ - public function dump() - { - // Parse the file - $this->parseFile(); - - echo '
';
-            var_dump($this->parsed);
-        echo '
'; - } - - /** - * - * Init a new sheet - * - * @param str $title The sheet name - * @param str $orientation The sheet orientation - * @return $this - * - */ - public function sheet($title, $orientation = 'landscape') - { - - // Set title - $this->setSheetTitle($title); - - if($orientation instanceof \Closure) - { - // Require a view - if(!$this->view) - throw new \PHPExcel_Exception('Settings data for sheets inside closures can only be used when a view has been loaded. Use ->loadView(\'filename\')'); - - // Add sheet from callback - $this->addNewSheet($orientation); - } - else - { - // Set orientation - $this->setOrientation($orientation); - - // Create a new sheet - $this->excel->createSheet(); - $this->excel->setActiveSheetIndex($this->i); - $this->excel->getActiveSheet()->setTitle($this->sheetTitle); - } - - // Set orientation - $this->excel->getActiveSheet()->getPageSetup() - ->setOrientation($this->orientation) - ->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4) - ->setFitToPage(true) - ->setFitToWidth(1) - ->setFitToHeight(1); - - // Count number of sheets - $this->i++; - - // Return itself to chain - return $this; - } - - /** - * Set sheet title - * @param [type] $title [description] - */ - public function setSheetTitle($title) - { - $this->sheetTitle = e($title); - return $this; - } - - /** - * Set orientation - * @param [type] $orientation [description] - */ - public function setOrientation($orientation = 'landscape') - { - // Set page orientation - switch ($orientation) { - case 'portrait': - $this->orientation = PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT; - break; - - default: - $this->orientation = PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE; - break; - } - } - - /** - * Add a new sheet from a view render - * @param [type] $sheet [description] - */ - public function addNewSheet($sheet) - { - // Remove the first worksheet - if($this->i == 0) - $this->excel->removeSheetByIndex(0); - - // Not yet - $this->viewRendered = false; - - // Do callback - call_user_func($sheet, $this); - - // Make the view - $view = $this->makeView(); - - // Get active sheet - $newSheet = $view->getActiveSheet()->setTitle($this->sheetTitle); - - // Add our new sheet to the excel file - $this->excel->addExternalSheet($newSheet); - } - - /** - * - * Pass an array to the sheet to fill it with - * - * @param array $array The array to fill the sheet with - * @return $this - * - */ - public function with($key, $value = false) - { - // If key is an array, we are assigning data to a new excel file, - // create a new active sheet from that array - if(is_array($key)) - { - // Send the variables to the excel sheet - $this->excel - ->getActiveSheet() - ->fromArray($key); - } - else - { - return $this->addVars($key, $value); - } - - return $this; - } - - /** - * Add vars to the data array - * @param [type] $key [description] - * @param boolean $value [description] - */ - public function addVars($key, $value = false) - { - $this->data[$key] = $value; - return $this; - } - - /** - * - * Export the file to a given filetype - * - * @param str $ext The file extension - * @return $this - * - */ - public function export($ext = 'xls') - { - - // Set the extension - $this->ext = $ext; - - // Render the XLS - $this->render(); - - // Set the headers - $this->setHeaders(); - - // Export the file - $this->object->save('php://output'); - - exit; - } - - /** - * - * Export the file to a given filetype - * - * @param str $ext The file extension - * @param str $path The save path - * @return $this - * - */ - public function save($ext = 'xls', $path = false) - { - return $this->store($ext, $path); - } - - /** - * - * Store the excel file to the server without a download popup - * - * @param str $ext The file extension - * @param str $path The save path - * @return $this - * - */ - public function store($ext = 'xls', $path = false, $returnInfo = false) - { - - // Set the default path - if($path == false) - { - $path = $this->config->get('excel::path'); - } - - // Trim of slashes, to makes sure we won't add them double. - $path = rtrim($path, '/'); - //$path = ltrim($path, '/'); - - // Set the extension - $this->ext = $ext; - - // Render the XLS - $this->render(); - - $toStore = $path . '/' . $this->title . '.' . $this->ext; - - // Save the file to specified location - $this->object->save($toStore); - - - if($returnInfo) - { - - // Send back information about the stored file - return array( - 'full' => $toStore, - 'path' => $path, - 'file' => $this->title . '.' . $this->ext, - 'title' => $this->title, - 'ext' => $this->ext - ); - - } - - return $this; - - } - - /** - * - * Convert the file to a given filetype - * - * @param str $ext The file extension - * @return $this - * - */ - public function convert($ext = 'xls') - { - - // Parse the file - $this->parseFile(); - - // Reset the excel object - $this->excel = app('phpexcel'); - - // Remove the default worksheet - $this->excel->removeSheetByIndex(0); - - if($this->sheetCount > 1) - { - // Loop through the worksheets - foreach($this->parsed as $worksheet => $content) - { - // Set the sheet with content - $this->sheet($worksheet)->with($content); - } - } - else - { - // Set sheet with content - $this->sheet($this->title)->with($this->parsed); - } - - // Export the file - $this->export($ext); - - } - - /** - * - * Render the excel file - * - * @return obj $this->object The writer - * - */ - private function render() - { - // If a view was set, make that view - if($this->view) - $this->excel = $this->makeView(); - - // Set the render format - $this->format = $this->decodeFormat($this->ext); - - // Set to first sheet - $this->excel->setActiveSheetIndex(0); - - // Create the writer - return $this->object = PHPExcel_IOFactory::createWriter($this->excel, $this->format); - } - - /** - * Make the view and load the html - * @return [type] [description] - */ - protected function makeView($title = false) - { - if($this->view && !$this->viewRendered) - { - // Make the view - $html = $this->viewFactory->make($this->view, $this->data, $this->mergeData)->render(); - - // Load the html - $rendered = $this->loadHTML($html); - - // Set to rendered - $this->viewRendered = true; - - return $rendered; - - } - } - - /** - * - * Parse the file - * - * @return $this - * - */ - private function parseFile() - { - - if(!$this->isParsed) - { - - // Set worksheet count - $i = 0; - - // Set empty array - $parsed = array(); - - // Loop through the worksheets - foreach($this->excel->getWorksheetIterator() as $this->worksheet) - { - - // Set the active worksheet - $this->excel->setActiveSheetIndex($i); - - // Get the worksheet name - $title = $this->excel->getActiveSheet()->getTitle(); - - // Convert to labels - if($this->firstRowAsLabel !== false) - { - // Fetch the labels - $this->labels = $this->getLabels(); - } - - // Get the sheet count - $this->sheetCount = $this->excel->getSheetCount(); - - // If we have more than 1 worksheet, seperate them - if($this->sheetCount > 1) - { - - // Parse the rows into seperate worksheets - $parsed[$title] = $this->parseRows(); - - } - else - { - // Parse the rows, but neglect the worksheet title - $parsed = $this->parseRows(); - } - - $i++; - - } - - - // Limit the result - if($this->limit !== false) - { - $this->parsed = array_slice($parsed, $this->limit[1], $this->limit[0]); - } - else - { - $this->parsed = $parsed; - } - - } - - $this->isParsed = true; - - // Return itself - return $this; - } - - /** - * - * Get the labels - * - * @return $this - * - */ - private function getLabels() - { - - // Fetch the first row - $this->row = $this->worksheet->getRowIterator(1)->current(); - - // Set empty labels array - $this->labels = array(); - - // Loop through the cells - foreach ($this->row->getCellIterator() as $this->cell) { - - // Set labels - $this->labels[] = Str::slug($this->cell->getValue(), $this->seperator); - - } - - // Return the labels - return $this->labels; - } - - /** - * - * Parse the rows - * - * @return $this - * - */ - private function parseRows() - { - - // Set row index to 0 - - $this->r = 0; - - // Set empty parsedRow array - $parsedRow = array(); - - // If the first row is the label, ignore the first row - if($this->firstRowAsLabel !== false) - { - $ignore = 1; - } - else - { - $ignore = 0; - } - - // Loop through the rows inside the worksheet - foreach ($this->worksheet->getRowIterator() as $this->row) { - - // Ignore first row (this can be 0 or 1) - if($this->r >= $ignore) - { - // Set the array, always starting with 0, and fill it with parsed cells - $parsedRow[$this->r - $ignore] = $this->parseCells(); - } - - // Count the rows - $this->r++; - - } - - // Return the parsed array - return $parsedRow; - } - - /** - * - * Parse the cells - * - * @return $this - * - */ - private function parseCells() - { - - $i = 0; - $parsedCells = array(); - - // Set the cell iterator - $this->cellIterator = $this->row->getCellIterator(); - $this->cellIterator->setIterateOnlyExistingCells($this->ignoreEmpty); - - // Foreach cells - foreach ($this->cellIterator as $this->cell) { - - // Get the cell index - $index = PHPExcel_Cell::columnIndexFromString($this->cell->getColumn()); - - // Check how we need to save the parsed array - if($this->firstRowAsLabel !== false) - { - // Set label index - $index = $this->labels[$i]; - } - - // If the cell is a date time - if(PHPExcel_Shared_Date::isDateTime($this->cell)) - { - - // Check if we want to parse the dates - if ($this->formatDates !== false) - { - - // Convert excel time to php date object - $value = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue()); - - // Format the date - $value = $value->format($this->dateFormat); - - // Use carbon to parse the time - if($this->useCarbon) - { - $value = Carbon::parse($value)->{$this->carbonMethod}(); - } - - } - else - { - // Format the date to a formatted string - $value = (string) PHPExcel_Style_NumberFormat::toFormattedString( - $this->cell->getCalculatedValue(), - $this->cell->getWorksheet()->getParent() - ->getCellXfByIndex($this->cell->getXfIndex()) - ->getNumberFormat() - ->getFormatCode() - ); - } - - - } - - // Check if we want calculated values or not - elseif($this->calculate !== false) - { - - // Get calculated value - $value = $this->cell->getCalculatedValue(); - - } - else - { - // Get real value - $value = $this->cell->getValue(); - } - - // Set the value - $parsedCells[$index] = $value; - - $i++; - - } - - // Return array with parsed cells - return $parsedCells; - - } - - /** - * Set headers - */ - private function setHeaders() - { - // Set the headers - switch($this->ext) - { - case 'xlsx': - header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); - break; - - case 'csv': - header('Content-type: application/csv'); - break; - - default: // xls - header('Content-Type: application/vnd.ms-excel'); - break; - } - - header('Content-Disposition: attachment;filename="' . $this->title . '.'. $this->ext .'"'); - header('Cache-Control: max-age=0'); - header('Cache-Control: max-age=1'); - header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past - header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified - header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 - header('Pragma: public'); // HTTP/1.0 - } - - /** - * - * Decode the format from extension - * - * @param str $ext The file extension - * @return str The format; - * - */ - private function decodeFormat($ext = false) - { - - switch($ext) - { - - case 'xls': - return 'Excel5'; - break; - - case 'xlsx': - return 'Excel2007'; - break; - - case 'csv': - return 'CSV'; - break; - - default: - return 'Excel5'; - break; - - } - - } - - /** - * - * Freeze or lock rows and columns - * - * @param string $pane rows and columns , default freeze the first row - * @return $this - * - * @author xiehai - * @example ->setFreeze() Freeze the first row - * ->setFreeze('B1') Freeze the first column (THE A COLUMN) - * ->setFreeze('B2') Freeze the first row and first column - * - */ - public function setFreeze($pane = 'A2') - { - $this->excel->getActiveSheet()->freezePane($pane); - return $this; - } - - /** - * Freeze the first row - * @return $this - */ - public function freezeFirstRow() - { - $this->setFreeze('A2'); - return $this; - } - - /** - * Freeze the first column - * @return $this - */ - public function freezeFirstColumn() - { - $this->setFreeze('B1'); - return $this; - } - - /** - * Freeze the first row and column - * @return $this - */ - public function freezeFirstRowAndColumn() - { - $this->setFreeze('B2'); - return $this; - } - - /** - * - * Set a range of cell borders - * - * @param string $pane Start and end of the cell (A1:F10) - * @param string $weight Border style (Reference setBorder style list) - * @return $this - * - * @author xiehai - * @example ->setBorder('A1:F10','thick') - * - */ - public function setBorder($pane = 'A1', $weight = 'thin') - { - /* - @ ~ Border styles list ~ @ - - PHPExcel_Style_Border::BORDER_NONE = 'none' - PHPExcel_Style_Border::BORDER_DASHDOT = 'dashDot' - PHPExcel_Style_Border::BORDER_DASHDOTDOT = 'dashDotDot' - PHPExcel_Style_Border::BORDER_DASHED = 'dashed' - PHPExcel_Style_Border::BORDER_DOTTED = 'dotted' - PHPExcel_Style_Border::BORDER_DOUBLE = 'double' - PHPExcel_Style_Border::BORDER_HAIR = 'hair' - PHPExcel_Style_Border::BORDER_MEDIUM = 'medium' - PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT = 'mediumDashDot' - PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot' - PHPExcel_Style_Border::BORDER_MEDIUMDASHED = 'mediumDashed' - PHPExcel_Style_Border::BORDER_SLANTDASHDOT = 'slantDashDot' - PHPExcel_Style_Border::BORDER_THICK = 'thick' - PHPExcel_Style_Border::BORDER_THIN = 'thin' - */ - - $weight = $pane == 'A1' ? 'none' : $weight; - - // Set all borders - $this->excel->getActiveSheet() - ->getStyle($pane) - ->getBorders() - ->getAllBorders() - ->setBorderStyle($weight); - - return $this; - } - - /** - * - * Set all cell borders - * - * @param string $weight Border style (Reference setBorder style list) - * @return $this - * - * @author xiehai - * @example Excel::create()->setAllBorder() Must follow the function of create() - * - */ - public function setAllBorder($weight = 'thin') - { - $styleArray = array( - 'borders' => array( - 'allborders' => array( - 'style' => $weight - ) - ) - ); - - // Apply the style - $this->excel->getDefaultStyle() - ->applyFromArray($styleArray); - - return $this; - } - - /** - * - * Set AutoFilter - * - * @return $this - * - * @author xiehai - * @example ->setAutoFilter() - * - */ - public function setAutoFilter(){ - $this->excel->getActiveSheet() - ->setAutoFilter($this->excel->getActiveSheet() - ->calculateWorksheetDimension()); - - return $this; - } - - /** - * - * Set the cell format of the column - * - * @return $this - * @param array $formats An array of cells you want to format columns - * - * @author xiehai - * @example ->setColumnFormat(array( - * 'B' => '0', - * 'D' => '0.00', - * 'F' => '@', - * 'F' => 'yyyy-mm-dd', - * ...... - * ) - * ) - * @uses This method can only be used before the with() method - * - */ - - /* - * @ ~ The Format list ~ @ - * - PHPExcel_Style_NumberFormat::FORMAT_GENERAL = 'General' - PHPExcel_Style_NumberFormat::FORMAT_TEXT = '@' - PHPExcel_Style_NumberFormat::FORMAT_NUMBER = '0' - PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00 = '0.00' - PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00' - PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-' - PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE = '0%' - PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00 = '0.00%' - PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd' - PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD = 'yy-mm-dd' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY = 'dd/mm/yy' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH = 'd/m/y' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS = 'd-m-y' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS = 'd-m' - PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS = 'm-y' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14 = 'mm-dd-yy' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15 = 'd-mmm-yy' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16 = 'd-mmm' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17 = 'mmm-yy' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22 = 'm/d/yy h:mm' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME = 'd/m/y h:mm' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1 = 'h:mm AM/PM' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3 = 'h:mm' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4 = 'h:mm:ss' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5 = 'mm:ss' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6 = 'h:mm:ss' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7 = 'i:s.S' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8 = 'h:mm:ss;@' - PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@' - PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-' - PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD = '$#,##0_-' - PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-' - */ - public function setColumnFormat(Array $formats){ - - // Loop through the columns - foreach ($formats as $column => $format) { - - // Change the format for a specific cell or range - $this->excel->getActiveSheet() - ->getStyle($column) - ->getNumberFormat() - ->setFormatCode($format); - } - - return $this; - } - - /** - * - * Set the cell width of the columns - * - * @return $this - * @param array $pane An array of column widths - * - * @author xiehai - * @example ->setColumnWidth(array( - * 'A' => '10', - * 'B' => '22', - * 'F' => '8', - * 'N' => '13', - * ...... - * ) - * ) - * - */ - public function setColumnWidth(Array $pane) - { - - foreach ($pane as $column => $width) { - $this->excel->getActiveSheet()->getColumnDimension($column)->setWidth($width); - } - - return $this; - } - - /** - * - * Set the columns you want to merge - * - * @return $this - * @param array $mergeColumn An array of columns you want to merge - * - * @author xiehai - * @example $mergeColumn = array( - * 'columns' => array('A','B','C','D'), - * 'rows' => array( - * array(2,3), - * array(5,11), - * ..... - * ) - * ); - * - */ - public function setMergeColumn(Array $mergeColumn) - { - - foreach ($mergeColumn['columns'] as $column) { - foreach ($mergeColumn['rows'] as $row) { - $this->mergeCells($column.$row[0].":".$column.$row[1]); - } - } - - return $this; - } - - /** - * - * Native merged cell method - * - * @return $this - * @param array $cells - * - * @author xiehai - * - */ - public function mergeCells($cells) - { - $this->excel->getActiveSheet()->mergeCells($cells); - return $this; - } - - /** - * Reset the parsed state - * @return [type] [description] - */ - public function reset() - { - // Reset i back to zero - $this->i = 0; - - // Reset sheet info - //$this->sheet = array(); - - // Reset parsed state - $this->isParsed = false; - - return $this; + $this->delimiter = $this->config->get('excel::delimiter', $this->delimiter); + $this->calculate = $this->config->get('excel::calculate', $this->calculate); + $this->ignoreEmpty = $this->config->get('excel::ignoreEmpty', $this->ignoreEmpty); + $this->dateFormat = $this->config->get('excel::date_format', $this->dateFormat); + $this->seperator = $this->config->get('excel::seperator', $this->seperator); } /** diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 9a905ac3b..4a47af693 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -1,8 +1,10 @@ bindPHPExcelClass(); + $this->bindClasses(); + $this->bindWriters(); $this->bindExcel(); } @@ -50,6 +54,27 @@ protected function bindPHPExcelClass() $this->app['phpexcel.readers.html'] = $this->app->share(function($app) { return new HTML_reader(); }); + + } + + /** + * Bind Classes + * @return [type] [description] + */ + protected function bindClasses() + { + + } + + /** + * Bind writers + * @return [type] [description] + */ + protected function bindWriters() + { + $this->app['excel.writer'] = $this->app->share(function($app) { + return new LaravelExcelWriter($app->make('Response')); + }); } /** @@ -61,7 +86,7 @@ protected function bindExcel() // Bind the Excel class and inject its dependencies $this->app['excel'] = $this->app->share(function($app) { - return new Excel($app['phpexcel'], $app['phpexcel.readers.html'], $app['config'], $app['view'], $app['files']); + return new Excel($app['phpexcel'], $app['excel.writer'], $app['phpexcel.readers.html'], $app['config'], $app['view'], $app['files']); }); } diff --git a/src/config/config.php b/src/config/config.php index 7e4e9543f..2399a3ff4 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -16,6 +16,62 @@ return array( + /* + |-------------------------------------------------------------------------- + | Default properties + |-------------------------------------------------------------------------- + | + | The default properties when creating a new Excel file + | + */ + 'properties' => array( + 'creator' => 'Maatwebsite', + 'lastModifiedBy' => 'Maatwebsite', + 'title' => 'Spreadsheet', + 'description' => 'Default spreadsheet export', + 'subject' => 'Spreadsheet export', + 'keywords' => 'maatwebsite, excel, export', + 'category' => 'Excel', + 'manager' => 'Maatwebsite', + 'company' => 'Maatwebsite', + ), + + /* + |-------------------------------------------------------------------------- + | Sheets settings + |-------------------------------------------------------------------------- + */ + 'sheets' => array( + + /* + |-------------------------------------------------------------------------- + | Default page setup + |-------------------------------------------------------------------------- + */ + 'pageSetup' => array( + 'orientation' => 'portrait', + 'paperSize' => '9', + 'scale' => '100', + 'fitToPage' => false, + 'fitToHeight' => true, + 'fitToWidth' => true, + 'columnsToRepeatAtLeft' => array('', ''), + 'rowsToRepeatAtTop' => array(0, 0), + 'horizontalCentered' => false, + 'verticalCentered' => false, + 'printArea' => null, + 'firstPageNumber' => null, + ), + + /* + |-------------------------------------------------------------------------- + | Autosize columns + |-------------------------------------------------------------------------- + */ + 'autosize' => true + + ), + /* |-------------------------------------------------------------------------- | Creator From c32898a82d604bc34d9798949fec27d7fb8144cc Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 12 Apr 2014 14:06:46 +0000 Subject: [PATCH 0003/1332] Corrupted xlsx fix --- .../Excel/Classes/LaravelExcelWorksheet.php | 276 +++++++++++++++++ src/Maatwebsite/Excel/Excel.php | 1 - .../Exceptions/LaravelExcelException.php | 5 + .../Excel/Writers/LaravelExcelWriter.php | 284 ++++++++++++++++++ src/config/config.php | 52 ++-- 5 files changed, 591 insertions(+), 27 deletions(-) create mode 100644 src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php create mode 100644 src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php create mode 100644 src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php new file mode 100644 index 000000000..55020bbfd --- /dev/null +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -0,0 +1,276 @@ +setParent($pParent); + } + + /** + * Set default page setup + */ + public function setDefaultPageSetup() + { + $pageSetup = $this->getPageSetup(); + + foreach($this->allowedPageSetup as $setup) + { + // set the setter + list($setter, $set) = $this->_setSetter($setup); + + // get the value + $value = \Config::get('excel::sheets.pageSetup.' . $setup, NULL); + + // Set the page setup value + if(!is_null($value)) + $pageSetup->{$setter}($value); + } + } + + // /** + // * Set the view + // * @param [type] $name [description] + // * @param array $data [description] + // * @param array $mergeData [description] + // */ + // public function setView($name, $data = array(), $mergeData = array()) + // { + // $this->getParent()->view = $name; + // $this->getParent()->data = $data; + // $this->getParent()->mergeData = $mergeData; + // return $this; + // } + + // /** + // * Get the view + // * @return [type] [description] + // */ + // public function getView() + // { + // return array( + // $this->getParent()->view, + // $this->getParent()->data, + // $this->getParent()->mergeData + // ); + // } + + /** + * Set data for the current sheet + * @param [type] $keys [description] + * @param boolean $value [description] + * @return [type] [description] + */ + public function with($key, $value = false) + { + // Add the vars + $this->_addVars($key, $value); + } + + /** + * Add vars to the data array + * @param [type] $key [description] + * @param boolean $value [description] + */ + protected function _addVars($key, $value = false) + { + // Add array of data + if(is_array($key)) + { + $this->data = array_merge($this->data, $key); + $this->fromArray($this->data); + } + + // Add seperate values + else + { + $this->data[$key] = $value; + } + } + + /** + * Set attributes + * @param [type] $key [description] + * @param [type] $params [description] + */ + public function _setAttributes($setter, $params) + { + // Set the setter and the key + list($setter, $key) = $this->_setSetter($setter); + + // If is page setup + if(in_array($key, $this->allowedPageSetup)) + { + // Set params + $params = is_array($params) ? $params : array($params); + + // Call the setter + return call_user_func_array(array($this->getPageSetup(), $setter), $params); + } + } + + /** + * Set the setter + * @param [type] $setter [description] + */ + protected function _setSetter($setter) + { + if(starts_with($setter, 'set')) + { + $key = lcfirst(str_replace('set', '', $setter)); + } + else + { + $key = $setter; + $setter = 'set' . ucfirst($key); + } + + // Return the setter method and the key + return array($setter, $key); + } + + /** + * Set the parent (excel object) + * @param [type] $parent [description] + */ + public function setParent($parent) + { + $this->_parent = $parent; + } + + /** + * Get the parent excel obj + * @return [type] [description] + */ + public function getParent() + { + return $this->_parent; + } + + /** + * Autosize column for document + * + * @return int + */ + public function setAutoSize($columns = false) + { + if(!is_array($columns) && $columns) + { + $toCol = $this->getHighestColumn(); + + $toCol++; + for ($i = 'A'; $i !== $toCol; $i++) { + $this->getColumnDimension($i)->setAutoSize(true); + } + } + elseif(is_array($columns)) + { + foreach($columns as $column) + { + $this->getColumnDimension($column)->setAutoSize(true); + } + } + + $this->calculateColumnWidths(); + + } + + /** + * Dynamically call methods + * @param [type] $method [description] + * @param [type] $params [description] + * @return [type] [description] + */ + public function __call($method, $params) + { + + // If the dynamic call starts with "with", add the var to the data array + if(starts_with($method, 'with')) + { + $key = lcfirst(str_replace('with', '', $method)); + $this->_addVars($key, reset($params)); + } + + // If it's a stter + elseif(starts_with($method, 'set') ) + { + // set the attribute + $this->_setAttributes($method, $params); + } + + return $this; + } + + /** + * Reset data on class destruct + */ + public function __destruct() + { + $this->data = array(); + } + +} diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index ec83da3de..f9172bb53 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -121,7 +121,6 @@ public function __construct(PHPExcel $excel, LaravelExcelWriter $writer, HTML_re */ public function create($title) { - // Set the default properties $this->excel->setDefaultProperties(array( 'title' => $title diff --git a/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php b/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php new file mode 100644 index 000000000..8e700ddac --- /dev/null +++ b/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php @@ -0,0 +1,5 @@ +response = $response; + } + + public function injectExcel($excel) + { + $this->excel = $excel; + $this->_reset(); + } + + /** + * Set the spreadsheet title + * @param [type] $title [description] + */ + public function setTitle($title) + { + $this->title = $title; + } + + /** + * Create a new sheet + * @param [type] $title [description] + * @param [type] $callback [description] + * @return [type] [description] + */ + public function sheet($title, $callback) + { + // Clone the active sheet + $this->sheet = clone $this->excel->getActiveSheet(); + + // Set the sheet title + $this->sheet->setTitle($title); + + // Set the default page setup + $this->sheet->setDefaultPageSetup(); + + // Autosize columns + $this->sheet->setAutosize(\Config::get('excel::sheets.autosize', false)); + + // Do the ballback + if($callback instanceof \Closure) + call_user_func($callback, $this->sheet); + + // Add the sheet + $this->excel->addSheet($this->sheet); + + return $this; + } + + /** + * Export the spreadsheet + * @return [type] [description] + */ + public function export($ext = 'xls') + { + // Set the extension + $this->ext = $ext; + + // Render the file + $this->render(); + + // Download the file + $this->download(); + } + + /** + * Download a file + * @return [type] [description] + */ + public function download() + { + // Set the headers + $this->_setHeaders(array( + + 'Content-Type' => $this->contentType, + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.' . $this->ext . '"', + 'Cache-Control' => 'max-age=0', + 'Cache-Control' => 'max-age=1', + 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past + 'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'), + 'Cache-Control' => 'cache, must-revalidate', + 'Pragma' => 'public' + + )); + + // Check if writer isset + if(!$this->writer) + throw new LaravelExcelException('[ERROR] No writer was set.'); + + // Download + $this->writer->save('php://output'); + + // End the script to prevent corrupted xlsx files + exit; + } + + /** + * Start render of a new spreadsheet + * @return [type] [description] + */ + public function render() + { + // There should be enough sheets to continue rendering + if($this->excel->getSheetCount() < 1) + throw new LaravelExcelException('[ERROR] Aborting spreadsheet render: no sheets were created.'); + + // Set the format + $this->_setFormat(); + + // Set the writer + $this->_setWriter(); + + // File has been rendered + $this->rendered = true; + } + + /** + * Set attributes + * @param [type] $setter [description] + * @param [type] $params [description] + */ + protected function _setAttribute($setter, $params) + { + // Get the key + $key = lcfirst(str_replace('set', '', $setter)); + + // If is an allowed property + if(in_array($key, $this->excel->allowedProperties)) + { + // Set the properties + call_user_func_array(array($this->excel->getProperties(), $setter), $params); + } + } + + /** + * Parse the data + * @return [type] [description] + */ + protected function _parseData() + { + // Fill the sheet with the array + $this->excel->getActiveSheet()->fromArray($this->excel->getActiveSheet()->data); + } + + /** + * Set the write format + */ + protected function _setFormat() + { + $this->ext = strtolower($this->ext); + + switch($this->ext) + { + case 'xls': + $this->format = 'Excel5'; + $this->contentType = 'application/vnd.ms-excel; charset=UTF-8'; + break; + + case 'xlsx': + $this->format = 'Excel2007'; + $this->contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'; + break; + + case 'csv': + $this->format = 'CSV'; + $this->contentType = 'application/csv; charset=UTF-8'; + break; + + default: + $this->format = 'Excel5'; + $this->contentType = 'application/vnd.ms-excel; charset=UTF-8'; + break; + } + } + + /** + * Set the writer + */ + protected function _setWriter() + { + return $this->writer = \PHPExcel_IOFactory::createWriter($this->excel, $this->format); + } + + /** + * Set the headers + */ + protected function _setHeaders($headers) + { + if ( headers_sent() ) throw new LaravelExcelException('[ERROR]: Headers already sent'); + + foreach($headers as $header => $value) + { + header($header . ': ' . $value); + } + } + + /** + * Reset the writer + * @return [type] [description] + */ + protected function _reset() + { + $this->excel->disconnectWorksheets(); + } + + /** + * Dynamically call methods + * @param [type] $method [description] + * @param [type] $params [description] + * @return [type] [description] + */ + public function __call($method, $params) + { + // If the dynamic call starts with "with", add the var to the data array + if(starts_with($method, 'set')) + { + $this->_setAttribute($method, $params); + } + + return $this; + } + + public function __destruct() + { + $this->excel->disconnectWorksheets(); + unset($this->excel); + } + +} \ No newline at end of file diff --git a/src/config/config.php b/src/config/config.php index 2399a3ff4..7845155d3 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -24,17 +24,17 @@ | The default properties when creating a new Excel file | */ - 'properties' => array( - 'creator' => 'Maatwebsite', - 'lastModifiedBy' => 'Maatwebsite', - 'title' => 'Spreadsheet', - 'description' => 'Default spreadsheet export', - 'subject' => 'Spreadsheet export', - 'keywords' => 'maatwebsite, excel, export', - 'category' => 'Excel', - 'manager' => 'Maatwebsite', - 'company' => 'Maatwebsite', - ), + // 'properties' => array( + // 'creator' => 'Maatwebsite', + // 'lastModifiedBy' => 'Maatwebsite', + // 'title' => 'Spreadsheet', + // 'description' => 'Default spreadsheet export', + // 'subject' => 'Spreadsheet export', + // 'keywords' => 'maatwebsite, excel, export', + // 'category' => 'Excel', + // 'manager' => 'Maatwebsite', + // 'company' => 'Maatwebsite', + // ), /* |-------------------------------------------------------------------------- @@ -48,27 +48,27 @@ | Default page setup |-------------------------------------------------------------------------- */ - 'pageSetup' => array( - 'orientation' => 'portrait', - 'paperSize' => '9', - 'scale' => '100', - 'fitToPage' => false, - 'fitToHeight' => true, - 'fitToWidth' => true, - 'columnsToRepeatAtLeft' => array('', ''), - 'rowsToRepeatAtTop' => array(0, 0), - 'horizontalCentered' => false, - 'verticalCentered' => false, - 'printArea' => null, - 'firstPageNumber' => null, - ), + // 'pageSetup' => array( + // 'orientation' => 'portrait', + // 'paperSize' => '9', + // 'scale' => '100', + // 'fitToPage' => false, + // 'fitToHeight' => true, + // 'fitToWidth' => true, + // 'columnsToRepeatAtLeft' => array('', ''), + // 'rowsToRepeatAtTop' => array(0, 0), + // 'horizontalCentered' => false, + // 'verticalCentered' => false, + // 'printArea' => null, + // 'firstPageNumber' => null, + // ), /* |-------------------------------------------------------------------------- | Autosize columns |-------------------------------------------------------------------------- */ - 'autosize' => true + //'autosize' => true ), From 594bcc5cb4bb88f8b5997924471c84f3837773b4 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 12 Apr 2014 15:14:36 +0000 Subject: [PATCH 0004/1332] Sheet styles --- .../Excel/Classes/LaravelExcelWorksheet.php | 83 +++++++++++++++++++ .../Excel/Writers/LaravelExcelWriter.php | 32 ++++--- src/config/config.php | 52 ++++++------ 3 files changed, 130 insertions(+), 37 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 55020bbfd..c4415faaa 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -59,6 +59,14 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet 'orientation', 'paperSize', 'scale', 'fitToPage', 'fitToHeight', 'fitToWidth', 'columnsToRepeatAtLeft', 'rowsToRepeatAtTop', 'horizontalCentered', 'verticalCentered', 'printArea', 'firstPageNumber' ); + /** + * Allowed page setup + * @var array + */ + public $allowedStyles = array( + 'fontFamily', 'fontSize' + ); + /** * Create a new worksheet * @@ -171,6 +179,80 @@ public function _setAttributes($setter, $params) // Call the setter return call_user_func_array(array($this->getPageSetup(), $setter), $params); } + + // If is a style + elseif(in_array($key, $this->allowedStyles) ) + { + $this->setDefaultStyles($setter, $key, $params); + } + } + + /** + * Set default styles + * @param [type] $setter [description] + * @param [type] $key [description] + * @param [type] $params [description] + */ + protected function setDefaultStyles($setter, $key, $params) + { + $caller = $this->getDefaultStyle(); + $params = is_array($params) ? $params : array($params); + + if(str_contains($key, 'font')) + return $this->setFontStyle($caller, $setter, $key, $params); + + return call_user_func_array(array($caller, $setter), $params); + } + + /** + * Set default styles by array + * @param [type] $styles [description] + */ + public function setStyle($styles) + { + $this->getDefaultStyle()->applyFromArray($styles); + } + + /** + * Set the font + * @param [type] $fonts [description] + * @return [type] [description] + */ + public function setFont($fonts) + { + foreach($fonts as $key => $value) + { + $this->setFontStyle($this->getDefaultStyle(), $key, $key, $value); + } + } + + /** + * Set default font styles + * @param [type] $caller [description] + * @param [type] $setter [description] + * @param [type] $key [description] + * @param [type] $params [description] + */ + protected function setFontStyle($caller, $setter, $key, $params) + { + // Set caller to font + $caller = $caller->getFont(); + $params = is_array($params) ? $params : array($params); + + // Clean the setter name + $key = lcfirst(str_replace('font', '', $key)); + + // Get setter method + list($setter, $key) = $this->_setSetter($key); + + switch($key) + { + case 'family': + $setter = 'setName'; + break; + } + + return call_user_func_array(array($caller, $setter), $params); } /** @@ -271,6 +353,7 @@ public function __call($method, $params) public function __destruct() { $this->data = array(); + $this->_parent->_cellXfCollection = array(); } } diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 9921ba424..5c3c55cb9 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -49,6 +49,12 @@ class LaravelExcelWriter { */ protected $rendered = false; + /** + * Sheet count + * @var integer + */ + protected $sheetCount = -1; + /** * Construct new writer */ @@ -78,7 +84,7 @@ public function setTitle($title) * @param [type] $callback [description] * @return [type] [description] */ - public function sheet($title, $callback) + public function sheet($title, $callback = false) { // Clone the active sheet $this->sheet = clone $this->excel->getActiveSheet(); @@ -99,6 +105,20 @@ public function sheet($title, $callback) // Add the sheet $this->excel->addSheet($this->sheet); + // Count sheets + $this->sheetCount++; + + return $this; + } + + /** + * Add data + * @param [type] $array [description] + * @return [type] [description] + */ + public function with($array) + { + $this->excel->getSheet($this->sheetCount)->fromArray($array); return $this; } @@ -187,16 +207,6 @@ protected function _setAttribute($setter, $params) } } - /** - * Parse the data - * @return [type] [description] - */ - protected function _parseData() - { - // Fill the sheet with the array - $this->excel->getActiveSheet()->fromArray($this->excel->getActiveSheet()->data); - } - /** * Set the write format */ diff --git a/src/config/config.php b/src/config/config.php index 7845155d3..2399a3ff4 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -24,17 +24,17 @@ | The default properties when creating a new Excel file | */ - // 'properties' => array( - // 'creator' => 'Maatwebsite', - // 'lastModifiedBy' => 'Maatwebsite', - // 'title' => 'Spreadsheet', - // 'description' => 'Default spreadsheet export', - // 'subject' => 'Spreadsheet export', - // 'keywords' => 'maatwebsite, excel, export', - // 'category' => 'Excel', - // 'manager' => 'Maatwebsite', - // 'company' => 'Maatwebsite', - // ), + 'properties' => array( + 'creator' => 'Maatwebsite', + 'lastModifiedBy' => 'Maatwebsite', + 'title' => 'Spreadsheet', + 'description' => 'Default spreadsheet export', + 'subject' => 'Spreadsheet export', + 'keywords' => 'maatwebsite, excel, export', + 'category' => 'Excel', + 'manager' => 'Maatwebsite', + 'company' => 'Maatwebsite', + ), /* |-------------------------------------------------------------------------- @@ -48,27 +48,27 @@ | Default page setup |-------------------------------------------------------------------------- */ - // 'pageSetup' => array( - // 'orientation' => 'portrait', - // 'paperSize' => '9', - // 'scale' => '100', - // 'fitToPage' => false, - // 'fitToHeight' => true, - // 'fitToWidth' => true, - // 'columnsToRepeatAtLeft' => array('', ''), - // 'rowsToRepeatAtTop' => array(0, 0), - // 'horizontalCentered' => false, - // 'verticalCentered' => false, - // 'printArea' => null, - // 'firstPageNumber' => null, - // ), + 'pageSetup' => array( + 'orientation' => 'portrait', + 'paperSize' => '9', + 'scale' => '100', + 'fitToPage' => false, + 'fitToHeight' => true, + 'fitToWidth' => true, + 'columnsToRepeatAtLeft' => array('', ''), + 'rowsToRepeatAtTop' => array(0, 0), + 'horizontalCentered' => false, + 'verticalCentered' => false, + 'printArea' => null, + 'firstPageNumber' => null, + ), /* |-------------------------------------------------------------------------- | Autosize columns |-------------------------------------------------------------------------- */ - //'autosize' => true + 'autosize' => true ), From fdd18685cc4dfca8ddc78ec45ce01080a822ec08 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 16 Apr 2014 12:25:29 +0000 Subject: [PATCH 0005/1332] Fix autofilter functionality --- composer.json | 2 +- .../Excel/Classes/LaravelExcelWorksheet.php | 11 ++++++++++ src/Maatwebsite/Excel/Classes/PHPExcel.php | 2 +- src/Maatwebsite/Excel/Excel.php | 4 +++- src/Maatwebsite/Excel/Readers/HTML_reader.php | 4 ++-- .../Excel/Writers/LaravelExcelWriter.php | 20 ++++++++++++++++--- 6 files changed, 35 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index b183de9ee..00cc25f3c 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "illuminate/support": "4.x", "illuminate/config": "4.x", "illuminate/filesystem": "4.x", - "phpoffice/phpexcel": "1.8.*" + "phpoffice/phpexcel": "1.8.0" }, "autoload": { "classmap": [ diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index c4415faaa..69b1b23ed 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -321,6 +321,17 @@ public function setAutoSize($columns = false) } + /** + * Set the auto filter + * @param boolean $value [description] + */ + public function setAutoFilter($value = false) + { + $value = $value ? $value : $this->calculateWorksheetDimension(); + parent::setAutoFilter($value); + return $this; + } + /** * Dynamically call methods * @param [type] $method [description] diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index 5cee8c7f5..ae24350fd 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -102,7 +102,7 @@ public function setDefaultProperties($custom) // get the value $value = in_array($prop, array_keys($custom)) ? $custom[$prop] : \Config::get('excel::properties.' . $prop, NULL); - // set the propertie + // set the property $properties->{$method}($value); } } diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index f9172bb53..8a118863b 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -17,7 +17,7 @@ /** * Laravel wrapper for PHPEXcel * - * @version 0.3.0 + * @version 0.4.0 * @package maatwebsite/excel * @author Maatwebsite * @contributors Maatwebsite, mewben, hicode, lollypopgr, floptwo, jonwhittlestone, BoHolm @@ -126,6 +126,8 @@ public function create($title) 'title' => $title )); + $this->excel->disconnectWorksheets(); + // Inject our excel object $this->writer->injectExcel($this->excel); diff --git a/src/Maatwebsite/Excel/Readers/HTML_reader.php b/src/Maatwebsite/Excel/Readers/HTML_reader.php index 4be28ceee..124f881c0 100644 --- a/src/Maatwebsite/Excel/Readers/HTML_reader.php +++ b/src/Maatwebsite/Excel/Readers/HTML_reader.php @@ -131,10 +131,10 @@ class HTML_reader extends \PHPExcel_Reader_HTML * @return PHPExcel * @throws PHPExcel_Reader_Exception */ - public function load($pFilename, $isString = false) + public function load($pFilename, $isString = false, $objPHPExcel = false) { // Create new PHPExcel - $objPHPExcel = new \PHPExcel(); + $objPHPExcel = $objPHPExcel ? $objPHPExcel : new \PHPExcel(); // Load into this instance return $this->loadIntoExisting($pFilename, $objPHPExcel, $isString); diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 5c3c55cb9..4c5cac858 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -107,7 +107,6 @@ public function sheet($title, $callback = false) // Count sheets $this->sheetCount++; - return $this; } @@ -118,7 +117,7 @@ public function sheet($title, $callback = false) */ public function with($array) { - $this->excel->getSheet($this->sheetCount)->fromArray($array); + $this->fromArray($array); return $this; } @@ -276,12 +275,27 @@ protected function _reset() */ public function __call($method, $params) { + // Call a php excel method + if(method_exists($this->excel, $method)) + { + // Call the method from the excel object with the given params + return call_user_func_array(array($this->excel, $method), $params); + } + + // Call a php excel sheet method + elseif(method_exists($this->excel->getSheet($this->sheetCount), $method)) + { + // Call the method from the excel object with the given params + return call_user_func_array(array($this->excel->getSheet($this->sheetCount), $method), $params); + } + // If the dynamic call starts with "with", add the var to the data array - if(starts_with($method, 'set')) + elseif(starts_with($method, 'set')) { $this->_setAttribute($method, $params); } + return $this; } From 532a0085064e4ee5520bf4808ba563262e1e6592 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 16 Apr 2014 12:35:13 +0000 Subject: [PATCH 0006/1332] FreezePane --- .../Excel/Classes/LaravelExcelWorksheet.php | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 69b1b23ed..48044d2cd 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -332,6 +332,55 @@ public function setAutoFilter($value = false) return $this; } + /** + * + * Freeze or lock rows and columns + * + * @param string $pane rows and columns , default freeze the first row + * @return $this + * + * @author xiehai + * @example ->setFreeze() Freeze the first row + * ->setFreeze('B1') Freeze the first column (THE A COLUMN) + * ->setFreeze('B2') Freeze the first row and first column + * + */ + public function setFreeze($pane = 'A2') + { + $this->freezePane($pane); + return $this; + } + + /** + * Freeze the first row + * @return $this + */ + public function freezeFirstRow() + { + $this->setFreeze('A2'); + return $this; + } + + /** + * Freeze the first column + * @return $this + */ + public function freezeFirstColumn() + { + $this->setFreeze('B1'); + return $this; + } + + /** + * Freeze the first row and column + * @return $this + */ + public function freezeFirstRowAndColumn() + { + $this->setFreeze('B2'); + return $this; + } + /** * Dynamically call methods * @param [type] $method [description] From 0fe060a9c91203cc8befdbc95226b2f83309bcbc Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 16 Apr 2014 13:37:23 +0000 Subject: [PATCH 0007/1332] View parser --- composer.json | 2 +- .../Excel/Classes/LaravelExcelWorksheet.php | 112 +++++++++++++----- src/Maatwebsite/Excel/Classes/PHPExcel.php | 2 +- src/Maatwebsite/Excel/Excel.php | 5 +- .../Excel/ExcelServiceProvider.php | 30 ++++- src/Maatwebsite/Excel/Parsers/ViewParser.php | 83 +++++++++++++ src/Maatwebsite/Excel/Readers/HTML_reader.php | 57 ++++----- .../Excel/Writers/LaravelExcelWriter.php | 4 +- 8 files changed, 230 insertions(+), 65 deletions(-) create mode 100644 src/Maatwebsite/Excel/Parsers/ViewParser.php diff --git a/composer.json b/composer.json index 00cc25f3c..b183de9ee 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "illuminate/support": "4.x", "illuminate/config": "4.x", "illuminate/filesystem": "4.x", - "phpoffice/phpexcel": "1.8.0" + "phpoffice/phpexcel": "1.8.*" }, "autoload": { "classmap": [ diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 48044d2cd..d6695eb64 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -1,6 +1,7 @@ getParent()->view = $name; - // $this->getParent()->data = $data; - // $this->getParent()->mergeData = $mergeData; - // return $this; - // } - - // /** - // * Get the view - // * @return [type] [description] - // */ - // public function getView() - // { - // return array( - // $this->getParent()->view, - // $this->getParent()->data, - // $this->getParent()->mergeData - // ); - // } + /** + * + * Load a View and convert to HTML + * + * @param string $view + * @param array $data + * @param array $mergeData + * @return static + * + */ + public function loadView($view, $data = array(), $mergeData = array()) + { + + // Init the parser + if(!$this->parser) + $this->parser = app('excel.parsers.view'); + + $this->parser->setView($view); + $this->parser->setData($data); + $this->parser->setMergeData($mergeData); + + return $this; + } + + /** + * Get the view + * @return [type] [description] + */ + public function getView() + { + return $this->parser; + } + + /** + * Return parsed sheet + * @return [type] [description] + */ + public function parsed() + { + // If parser is set, use it + if($this->parser) + return $this->parser->parse($this); + + // Else return the entire sheet + return $this; + } /** * Set data for the current sheet @@ -149,8 +188,12 @@ protected function _addVars($key, $value = false) // Add array of data if(is_array($key)) { + // Set the data $this->data = array_merge($this->data, $key); - $this->fromArray($this->data); + + // Create excel from array without a view + if(!$this->parser) + $this->fromArray($this->data); } // Add seperate values @@ -158,6 +201,10 @@ protected function _addVars($key, $value = false) { $this->data[$key] = $value; } + + // Set data to parser + if($this->parser) + $this->parser->setData($this->data); } /** @@ -381,6 +428,15 @@ public function freezeFirstRowAndColumn() return $this; } + /** + * Get the sheet index + * @return [type] [description] + */ + public function getSheetIndex() + { + return $this->_parent->getActiveSheetIndex(); + } + /** * Dynamically call methods * @param [type] $method [description] diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index ae24350fd..b78f87092 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -1,6 +1,7 @@ _workSheetCollection = array(); $this->_workSheetCollection[] = new LaravelExcelWorksheet($this); diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 8a118863b..2e7b8a597 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -13,6 +13,7 @@ use Illuminate\Config\Repository as Config; use Illuminate\Filesystem\Filesystem as File; use Maatwebsite\Excel\Writers\LaravelExcelWriter; +use Maatwebsite\Excel\Parsers\ViewParser; /** * Laravel wrapper for PHPEXcel @@ -95,12 +96,12 @@ class Excel * @param View $view [description] * @param File $file [description] */ - public function __construct(PHPExcel $excel, LaravelExcelWriter $writer, HTML_reader $htmlReader, Config $config, View $view, File $file) + public function __construct(PHPExcel $excel, LaravelExcelWriter $writer, ViewParser $parser, Config $config, View $view, File $file) { // Set Excel dependencies $this->excel = $excel; $this->writer = $writer; - $this->htmlReader = $htmlReader; + $this->parser = $parser; // Set Laravel classes $this->config = $config; diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 4a47af693..625c0d828 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -5,6 +5,7 @@ use Maatwebsite\Excel\Readers\HTML_reader; use Maatwebsite\Excel\Writers\LaravelExcelWriter; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; +use Maatwebsite\Excel\Parsers\ViewParser; class ExcelServiceProvider extends ServiceProvider { @@ -33,6 +34,8 @@ public function boot() */ public function register() { + $this->bindReaders(); + $this->bindParsers(); $this->bindPHPExcelClass(); $this->bindClasses(); $this->bindWriters(); @@ -49,21 +52,38 @@ protected function bindPHPExcelClass() $this->app['phpexcel'] = $this->app->share(function($app) { return new PHPExcel(); }); + } + /** + * Bind Classes + * @return [type] [description] + */ + protected function bindClasses() + { + + } + + /** + * Bind writers + * @return [type] [description] + */ + protected function bindReaders() + { // Bind the PHPExcel class $this->app['phpexcel.readers.html'] = $this->app->share(function($app) { return new HTML_reader(); }); - } /** - * Bind Classes + * Bind writers * @return [type] [description] */ - protected function bindClasses() + protected function bindParsers() { - + $this->app['excel.parsers.view'] = $this->app->share(function($app) { + return new ViewParser($app['phpexcel.readers.html']); + }); } /** @@ -86,7 +106,7 @@ protected function bindExcel() // Bind the Excel class and inject its dependencies $this->app['excel'] = $this->app->share(function($app) { - return new Excel($app['phpexcel'], $app['excel.writer'], $app['phpexcel.readers.html'], $app['config'], $app['view'], $app['files']); + return new Excel($app['phpexcel'], $app['excel.writer'], $app['excel.parsers.view'], $app['config'], $app['view'], $app['files']); }); } diff --git a/src/Maatwebsite/Excel/Parsers/ViewParser.php b/src/Maatwebsite/Excel/Parsers/ViewParser.php new file mode 100644 index 000000000..c4f0ad45a --- /dev/null +++ b/src/Maatwebsite/Excel/Parsers/ViewParser.php @@ -0,0 +1,83 @@ +reader = $reader; + } + + /** + * Parse the view + * @param [type] $sheet [description] + * @return [type] [description] + */ + public function parse($sheet) + { + $html = \View::make($this->view, $this->data, $this->mergeData)->render(); + return $this->_loadHTML($sheet, $html); + } + + /** + * Load the HTML + * @param [type] $sheet [description] + * @param [type] $html [description] + * @return [type] [description] + */ + protected function _loadHTML($sheet, $html) + { + return $this->reader->load($html, true, $sheet)->getActiveSheet(); + } + + /** + * Set the view + * @param [type] $view [description] + */ + public function setView($view) + { + $this->view = $view; + } + + /** + * Set the data + * @param array $data [description] + */ + public function setData($data = array()) + { + $this->data = array_merge($this->data, $data); + } + + /** + * Set the merge data + * @param array $mergeData [description] + */ + public function setMergeData($mergeData = array()) + { + $this->mergeData = array_merge($this->mergeData, $mergeData); + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Readers/HTML_reader.php b/src/Maatwebsite/Excel/Readers/HTML_reader.php index 124f881c0..99ca7f8f3 100644 --- a/src/Maatwebsite/Excel/Readers/HTML_reader.php +++ b/src/Maatwebsite/Excel/Readers/HTML_reader.php @@ -35,6 +35,7 @@ use \PHPExcel_Style_Fill; use \PHPExcel_Style_Font; use \PHPExcel_Style_Alignment; +use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; class HTML_reader extends \PHPExcel_Reader_HTML { @@ -131,24 +132,33 @@ class HTML_reader extends \PHPExcel_Reader_HTML * @return PHPExcel * @throws PHPExcel_Reader_Exception */ - public function load($pFilename, $isString = false, $objPHPExcel = false) + public function load($pFilename, $isString = false, $obj = false) { - // Create new PHPExcel - $objPHPExcel = $objPHPExcel ? $objPHPExcel : new \PHPExcel(); - // Load into this instance + if($obj instanceof \PHPExcel) + { + // Load into this instance + return $this->loadIntoExisting($pFilename, $obj, $isString); + } + elseif($obj instanceof LaravelExcelWorksheet) + { + // Load into this instance + return $this->loadIntoExistingSheet($pFilename, $obj, $isString); + } + + $objPHPExcel = $obj ? $obj : new \PHPExcel(); return $this->loadIntoExisting($pFilename, $objPHPExcel, $isString); } /** - * Loads PHPExcel from file into PHPExcel instance + * Loads HTML from file into sheet instance * * @param string $pFilename - * @param PHPExcel $objPHPExcel + * @param LaravelExcelWorksheet $sheet * @return PHPExcel * @throws PHPExcel_Reader_Exception */ - public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel, $isString = false) + public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, $isString = false) { $isHtmlFile = FALSE; @@ -171,21 +181,14 @@ public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel, $isString = } } - // Create new PHPExcel - while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) { - $objPHPExcel->createSheet(); - } - $objPHPExcel->setActiveSheetIndex( $this->_sheetIndex ); - // Create a new DOM object $dom = new \domDocument; - // Reload the HTML file into the DOM object // Check if we need to load the file or the HTML if($isHtmlFile) { // Load HTML from file - $loaded = $dom->loadHTMLFile($pFilename); + $loaded = @$dom->loadHTMLFile($pFilename); } else { @@ -204,10 +207,10 @@ public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel, $isString = $row = 0; $column = 'A'; $content = ''; - $this->_processDomElement($dom,$objPHPExcel->getActiveSheet(),$row,$column,$content); - $this->autosizeColumn($objPHPExcel); + $this->_processDomElement($dom,$sheet,$row,$column,$content); + $this->autosizeColumn($sheet); - return $objPHPExcel; + return $sheet; } /** @@ -215,18 +218,18 @@ public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel, $isString = * * @return int */ - public static function autosizeColumn(\PHPExcel $objPHPExcel) + public function autosizeColumn($sheet) { - foreach ($objPHPExcel->getAllSheets() as $sheet) { - $toCol = $sheet->getHighestColumn(); - - $toCol++; - for ($i = 'A'; $i !== $toCol; $i++) { - $sheet->getColumnDimension($i)->setAutoSize(true); - } + $toCol = $sheet->getHighestColumn(); - $sheet->calculateColumnWidths(); + $toCol++; + for ($i = 'A'; $i !== $toCol; $i++) { + $sheet->getColumnDimension($i)->setAutoSize(true); } + + $sheet->calculateColumnWidths(); + + return $sheet; } private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, &$cellContent){ diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 4c5cac858..991681d8a 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -103,7 +103,7 @@ public function sheet($title, $callback = false) call_user_func($callback, $this->sheet); // Add the sheet - $this->excel->addSheet($this->sheet); + $this->excel->addSheet($this->sheet->parsed()); // Count sheets $this->sheetCount++; @@ -178,6 +178,8 @@ public function render() if($this->excel->getSheetCount() < 1) throw new LaravelExcelException('[ERROR] Aborting spreadsheet render: no sheets were created.'); + // dd($this->getView()); + // Set the format $this->_setFormat(); From c962b5a49fc246999853ee8c3473c690172077dd Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 16 Apr 2014 18:33:25 +0200 Subject: [PATCH 0008/1332] Couple of style parsing fixes --- .gitignore | 0 LICENSE | 0 .../Excel/Classes/LaravelExcelWorksheet.php | 16 ++++- src/Maatwebsite/Excel/Excel.php | 10 +++ src/Maatwebsite/Excel/Facades/Excel.php | 0 src/Maatwebsite/Excel/Readers/HTML_reader.php | 64 ++++++++++++++----- .../Excel/Writers/LaravelExcelWriter.php | 1 - 7 files changed, 72 insertions(+), 19 deletions(-) mode change 100644 => 100755 .gitignore mode change 100644 => 100755 LICENSE mode change 100644 => 100755 src/Maatwebsite/Excel/Facades/Excel.php mode change 100644 => 100755 src/Maatwebsite/Excel/Readers/HTML_reader.php diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index d6695eb64..126017278 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -131,7 +131,6 @@ public function setDefaultPageSetup() */ public function loadView($view, $data = array(), $mergeData = array()) { - // Init the parser if(!$this->parser) $this->parser = app('excel.parsers.view'); @@ -437,6 +436,21 @@ public function getSheetIndex() return $this->_parent->getActiveSheetIndex(); } + /** + * Get style for cell + * + * @param string $pCellCoordinate Cell coordinate to get style for + * @return PHPExcel_Style + * @throws PHPExcel_Exception + */ + public function getStyle($pCellCoordinate = 'A1') + { + // set cell coordinate as active + $this->setSelectedCells($pCellCoordinate); + + return $this->_parent->getCellXfSupervisor(); + } + /** * Dynamically call methods * @param [type] $method [description] diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 2e7b8a597..25b3e9afa 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -14,6 +14,7 @@ use Illuminate\Filesystem\Filesystem as File; use Maatwebsite\Excel\Writers\LaravelExcelWriter; use Maatwebsite\Excel\Parsers\ViewParser; +use Maatwebsite\Excel\Exceptions\LaravelExcelException; /** * Laravel wrapper for PHPEXcel @@ -139,6 +140,15 @@ public function create($title) return $this->writer; } + /** + * Load a view + * @return [type] [description] + */ + public function loadView() + { + throw new LaravelExcelException('[ERROR] Only use the loadView() from inside the sheet closure'); + } + /** * Set defaults */ diff --git a/src/Maatwebsite/Excel/Facades/Excel.php b/src/Maatwebsite/Excel/Facades/Excel.php old mode 100644 new mode 100755 diff --git a/src/Maatwebsite/Excel/Readers/HTML_reader.php b/src/Maatwebsite/Excel/Readers/HTML_reader.php old mode 100644 new mode 100755 index 99ca7f8f3..d713e6272 --- a/src/Maatwebsite/Excel/Readers/HTML_reader.php +++ b/src/Maatwebsite/Excel/Readers/HTML_reader.php @@ -54,11 +54,15 @@ class HTML_reader extends \PHPExcel_Reader_HTML */ private $_sheetIndex = 0; + /** + * HTML tags formatting settings + * @var array + */ private $_formats = array( - 'h1' => array( + 'th' => array( 'font' => array( 'bold' => true, - 'size' => 24, + 'size' => 12, ), ), 'strong' => array( @@ -78,37 +82,43 @@ class HTML_reader extends \PHPExcel_Reader_HTML 'italic' => true, 'size' => 12, ), + ), + 'h1' => array( + 'font' => array( + 'bold' => true, + 'size' => 24, + ), ), // Bold, 24pt 'h2' => array( 'font' => array( 'bold' => true, 'size' => 18, - ), - ), // Bold, 18pt + ), + ), // Bold, 18pt 'h3' => array( 'font' => array( 'bold' => true, 'size' => 13.5, - ), - ), // Bold, 13.5pt + ), + ), // Bold, 13.5pt 'h4' => array( 'font' => array( 'bold' => true, 'size' => 12, - ), - ), // Bold, 12pt + ), + ), // Bold, 12pt 'h5' => array( 'font' => array( 'bold' => true, 'size' => 10, - ), - ), // Bold, 10pt + ), + ), // Bold, 10pt 'h6' => array( 'font' => array( 'bold' => true, 'size' => 7.5, - ), - ), // Bold, 7.5pt + ), + ), // Bold, 7.5pt 'a' => array( 'font' => array( 'underline' => true, @@ -452,6 +462,9 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, ++$row; break; case 'th' : + $this->_processHeadings($child, $sheet, $row, $column, $cellContent); + ++$column; + break; case 'td' : // echo 'START OF TABLE ' , $this->_tableLevel , ' CELL
'; $this->_processDomElement($child,$sheet,$row,$column,$cellContent); @@ -516,6 +529,27 @@ private function _flushCell($sheet,$column,$row,&$cellContent) { $cellContent = (string) ''; } + /** + * Process table headings + * @param [type] $child [description] + * @param [type] $sheet [description] + * @param [type] $row [description] + * @param [type] $column [description] + * @return [type] [description] + */ + protected function _processHeadings($child, $sheet, $row, $column, $cellContent) + { + + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_flushCell($sheet,$column,$row,$cellContent); + + if (isset($this->_formats[$child->nodeName])) { + $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + } + + return $sheet; + } + /** * Parse colspans * @param [type] $sheet [description] @@ -662,11 +696,6 @@ protected function parseInlineStyles($sheet, $column, $row, $styleTag) switch($name) { - // COLSPAN - case 'colspan': - dd($value); - break; - // BACKGROUND case 'background': $value = str_replace('#', '', $value); @@ -679,6 +708,7 @@ protected function parseInlineStyles($sheet, $column, $row, $styleTag) ) ) ); + dd($cells); break; // TEXT COLOR diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 991681d8a..646f98ad3 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -102,7 +102,6 @@ public function sheet($title, $callback = false) if($callback instanceof \Closure) call_user_func($callback, $this->sheet); - // Add the sheet $this->excel->addSheet($this->sheet->parsed()); // Count sheets From c3e781c3ae10b269858e0d06cdf8638951a65b7d Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 28 Apr 2014 19:29:33 +0000 Subject: [PATCH 0009/1332] Re-added store method --- .gitignore | 0 LICENSE | 0 src/Maatwebsite/Excel/Facades/Excel.php | 0 src/Maatwebsite/Excel/Readers/HTML_reader.php | 1 - .../Excel/Writers/LaravelExcelWriter.php | 69 ++++++++++++++++++- src/config/config.php | 2 +- 6 files changed, 67 insertions(+), 5 deletions(-) mode change 100755 => 100644 .gitignore mode change 100755 => 100644 LICENSE mode change 100755 => 100644 src/Maatwebsite/Excel/Facades/Excel.php mode change 100755 => 100644 src/Maatwebsite/Excel/Readers/HTML_reader.php diff --git a/.gitignore b/.gitignore old mode 100755 new mode 100644 diff --git a/LICENSE b/LICENSE old mode 100755 new mode 100644 diff --git a/src/Maatwebsite/Excel/Facades/Excel.php b/src/Maatwebsite/Excel/Facades/Excel.php old mode 100755 new mode 100644 diff --git a/src/Maatwebsite/Excel/Readers/HTML_reader.php b/src/Maatwebsite/Excel/Readers/HTML_reader.php old mode 100755 new mode 100644 index d713e6272..ae40e8771 --- a/src/Maatwebsite/Excel/Readers/HTML_reader.php +++ b/src/Maatwebsite/Excel/Readers/HTML_reader.php @@ -708,7 +708,6 @@ protected function parseInlineStyles($sheet, $column, $row, $styleTag) ) ) ); - dd($cells); break; // TEXT COLOR diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 646f98ad3..6d2d98052 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -37,6 +37,12 @@ class LaravelExcelWriter { */ public $ext = 'xls'; + /** + * Path the file will be stored to + * @var [type] + */ + public $storagePath = 'app/storage/uploads'; + /** * Header Content-type * @var [type] @@ -136,6 +142,48 @@ public function export($ext = 'xls') $this->download(); } + /** + * Store the excel file to the server + * @param string $ext [description] + * @param boolean $path [description] + * @param boolean $returnInfo [description] + * @return [type] [description] + */ + public function store($ext = 'xls', $path = false, $returnInfo = false) + { + // Set the storage path + $this->_setStoragePath($path); + + // Set the extension + $this->ext = $ext; + + // Render the XLS + $this->render(); + + // Set the storage path and file + $toStore = $this->storagePath . '/' . $this->title . '.' . $this->ext; + + // Save the file to specified location + $this->writer->save($toStore); + + // Return file info + if($returnInfo) + { + // Send back information about the stored file + return array( + 'full' => $toStore, + 'path' => $this->storagePath, + 'file' => $this->title . '.' . $this->ext, + 'title' => $this->title, + 'ext' => $this->ext + ); + + } + + // Return itself + return $this; + } + /** * Download a file * @return [type] [description] @@ -146,7 +194,7 @@ public function download() $this->_setHeaders(array( 'Content-Type' => $this->contentType, - 'Content-Disposition' => 'attachment; filename="' . $this->title . '.' . $this->ext . '"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.' . $this->ext . '"', 'Cache-Control' => 'max-age=0', 'Cache-Control' => 'max-age=1', 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past @@ -177,8 +225,6 @@ public function render() if($this->excel->getSheetCount() < 1) throw new LaravelExcelException('[ERROR] Aborting spreadsheet render: no sheets were created.'); - // dd($this->getView()); - // Set the format $this->_setFormat(); @@ -259,6 +305,23 @@ protected function _setHeaders($headers) } } + /** + * Set the storage path + * @var [type] + */ + protected function _setStoragePath($path = false) + { + // Get the default path + $path = $path ? $path : \Config::get('excel::path', base_path($this->storagePath)); + + // Trim of slashes, to makes sure we won't add them double + $this->storagePath = rtrim($path, '/'); + + // Make sure the storage path exists + if(!file_exists($this->storagePath)) + mkdir($this->storagePath, 0777); + } + /** * Reset the writer * @return [type] [description] diff --git a/src/config/config.php b/src/config/config.php index 2399a3ff4..69f061ea3 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -151,6 +151,6 @@ | */ - 'path' => base_path(), + 'path' => base_path('app/storage/uploads'), ); From 75247a8bc6360b5b2c65fc2ce3e489a7652b24de Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 28 Apr 2014 20:14:02 +0000 Subject: [PATCH 0010/1332] Start of Batch uploader + Html reader rename --- src/Maatwebsite/Excel/Excel.php | 39 ++++++-- .../Excel/ExcelServiceProvider.php | 6 +- src/Maatwebsite/Excel/Parsers/ViewParser.php | 4 +- .../Excel/Readers/BatchUploader.php | 97 +++++++++++++++++++ .../{HTML_reader.php => HtmlReader.php} | 2 +- .../Excel/Writers/LaravelExcelWriter.php | 82 +++++++++------- 6 files changed, 182 insertions(+), 48 deletions(-) create mode 100644 src/Maatwebsite/Excel/Readers/BatchUploader.php rename src/Maatwebsite/Excel/Readers/{HTML_reader.php => HtmlReader.php} (99%) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 25b3e9afa..1458599b3 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -8,6 +8,7 @@ use Illuminate\Support\Str; use \PHPExcel_Style_NumberFormat; use \PHPExcel_Worksheet_PageSetup; +use Maatwebsite\Excel\Readers\Batch; use Illuminate\View\Environment as View; use Maatwebsite\Excel\Readers\HTML_reader; use Illuminate\Config\Repository as Config; @@ -34,6 +35,12 @@ class Excel */ public $excel; + /** + * Batch object + * @var [type] + */ + public $batch; + /** * Html reader * @var [type] @@ -111,9 +118,6 @@ public function __construct(PHPExcel $excel, LaravelExcelWriter $writer, ViewPar // Set defaults $this->_setDefaults(); - - // Reset - $this->reset(); } /** @@ -140,12 +144,28 @@ public function create($title) return $this->writer; } + /** + * Batch import + * @return [type] [description] + */ + public function batch($files, $callback) + { + $this->batch = new Batch($files); + + // Do the ballback + if($callback instanceof \Closure) + call_user_func($callback, $this, $this->batch->getFiles()); + + return $this; + } + /** * Load a view * @return [type] [description] */ public function loadView() { + // Deprecated throw new LaravelExcelException('[ERROR] Only use the loadView() from inside the sheet closure'); } @@ -155,11 +175,11 @@ public function loadView() protected function _setDefaults() { // Set defaults - $this->delimiter = $this->config->get('excel::delimiter', $this->delimiter); - $this->calculate = $this->config->get('excel::calculate', $this->calculate); - $this->ignoreEmpty = $this->config->get('excel::ignoreEmpty', $this->ignoreEmpty); - $this->dateFormat = $this->config->get('excel::date_format', $this->dateFormat); - $this->seperator = $this->config->get('excel::seperator', $this->seperator); + $this->delimiter = $this->config->get('excel::delimiter', $this->delimiter); + $this->calculate = $this->config->get('excel::calculate', $this->calculate); + $this->ignoreEmpty = $this->config->get('excel::ignoreEmpty', $this->ignoreEmpty); + $this->dateFormat = $this->config->get('excel::date_format', $this->dateFormat); + $this->seperator = $this->config->get('excel::seperator', $this->seperator); } /** @@ -176,6 +196,7 @@ public function __call($method, $params) { $key = lcfirst(str_replace('with', '', $method)); $this->addVars($key, reset($params)); + return $this; } // Call a php excel method @@ -185,7 +206,7 @@ public function __call($method, $params) return call_user_func_array(array($this->excel, $method), $params); } - return $this; + throw new LaravelExcelException('Laravel Excel method ['. $method .'] does not exist'); } } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 625c0d828..d3c5ab99d 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -2,7 +2,7 @@ use Maatwebsite\Excel\Classes\PHPExcel; use Illuminate\Support\ServiceProvider; -use Maatwebsite\Excel\Readers\HTML_reader; +use Maatwebsite\Excel\Readers\Html; use Maatwebsite\Excel\Writers\LaravelExcelWriter; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; use Maatwebsite\Excel\Parsers\ViewParser; @@ -71,7 +71,7 @@ protected function bindReaders() { // Bind the PHPExcel class $this->app['phpexcel.readers.html'] = $this->app->share(function($app) { - return new HTML_reader(); + return new Html(); }); } @@ -93,7 +93,7 @@ protected function bindParsers() protected function bindWriters() { $this->app['excel.writer'] = $this->app->share(function($app) { - return new LaravelExcelWriter($app->make('Response')); + return new LaravelExcelWriter($app->make('Response'), $app['files']); }); } diff --git a/src/Maatwebsite/Excel/Parsers/ViewParser.php b/src/Maatwebsite/Excel/Parsers/ViewParser.php index c4f0ad45a..06b5f140a 100644 --- a/src/Maatwebsite/Excel/Parsers/ViewParser.php +++ b/src/Maatwebsite/Excel/Parsers/ViewParser.php @@ -1,6 +1,6 @@ reader = $reader; } diff --git a/src/Maatwebsite/Excel/Readers/BatchUploader.php b/src/Maatwebsite/Excel/Readers/BatchUploader.php new file mode 100644 index 000000000..6adc26900 --- /dev/null +++ b/src/Maatwebsite/Excel/Readers/BatchUploader.php @@ -0,0 +1,97 @@ +_setFiles($files); + } + + /** + * Get the files + * @return [type] [description] + */ + public function getFiles() + { + return $this->files; + } + + /** + * Set the batch files + * @param [type] $files [description] + */ + public function _setFiles($files) + { + // If the param is an array, these will be the files for the batch import + if(is_array($files)) + { + $this->files = $this->_getFilesByArray($files); + } + + // Get all the files inside a folder + elseif(is_string($files)) + { + $this->files = $this->_getFilesByFolder($files); + } + + // Check if files were found + if(empty($this->files)) + throw new LaravelExcelException('[ERROR]: No files were found. Batch terminated.'); + } + + /** + * Set files by array + * @param [type] $array [description] + * @return [type] [description] + */ + protected function _getFilesByArray($array) + { + // Make sure we have real paths + foreach($array as $i => $file) + { + $this->files[$i] = realpath($file) ? $file : base_path($file); + } + } + + /** + * Get all files inside a folder + * @param [type] $folder [description] + * @return [type] [description] + */ + protected function _getFilesByFolder($folder) + { + // Check if it's a real path + if(!realpath($folder)) + $folder = base_path($folder); + + // Find path names matching our pattern of excel extensions + $glob = glob($folder.'/*.{'. implode(',', $this->allowedFileExtensions) .'}', GLOB_BRACE); + + if ($glob === false) return array(); + + return array_filter($glob, function($file) { + return filetype($file) == 'file'; + }); + } +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Readers/HTML_reader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php similarity index 99% rename from src/Maatwebsite/Excel/Readers/HTML_reader.php rename to src/Maatwebsite/Excel/Readers/HtmlReader.php index ae40e8771..4f8a4550a 100644 --- a/src/Maatwebsite/Excel/Readers/HTML_reader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -37,7 +37,7 @@ use \PHPExcel_Style_Alignment; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; -class HTML_reader extends \PHPExcel_Reader_HTML +class Html extends \PHPExcel_Reader_HTML { /** diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 6d2d98052..3c901b725 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -2,6 +2,7 @@ use \Response; use Carbon\Carbon; +use Illuminate\Filesystem\Filesystem; use Maatwebsite\Excel\Exceptions\LaravelExcelException; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; @@ -63,10 +64,13 @@ class LaravelExcelWriter { /** * Construct new writer + * @param Response $response [description] + * @param FileSystem $files [description] */ - public function __construct(Response $response) + public function __construct(Response $response, FileSystem $filesystem) { $this->response = $response; + $this->filesystem = $filesystem; } public function injectExcel($excel) @@ -136,12 +140,43 @@ public function export($ext = 'xls') $this->ext = $ext; // Render the file - $this->render(); + $this->_render(); // Download the file $this->download(); } + /** + * Download a file + * @return [type] [description] + */ + public function download() + { + // Set the headers + $this->_setHeaders(array( + + 'Content-Type' => $this->contentType, + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.' . $this->ext . '"', + 'Cache-Control' => 'max-age=0', + 'Cache-Control' => 'max-age=1', + 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past + 'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'), + 'Cache-Control' => 'cache, must-revalidate', + 'Pragma' => 'public' + + )); + + // Check if writer isset + if(!$this->writer) + throw new LaravelExcelException('[ERROR] No writer was set.'); + + // Download + $this->writer->save('php://output'); + + // End the script to prevent corrupted xlsx files + exit; + } + /** * Store the excel file to the server * @param string $ext [description] @@ -158,7 +193,7 @@ public function store($ext = 'xls', $path = false, $returnInfo = false) $this->ext = $ext; // Render the XLS - $this->render(); + $this->_render(); // Set the storage path and file $toStore = $this->storagePath . '/' . $this->title . '.' . $this->ext; @@ -185,41 +220,21 @@ public function store($ext = 'xls', $path = false, $returnInfo = false) } /** - * Download a file - * @return [type] [description] + * Store the excel file to the server + * @param str $ext The file extension + * @param str $path The save path + * @return $this */ - public function download() + public function save($ext = 'xls', $path = false, $returnInfo = false) { - // Set the headers - $this->_setHeaders(array( - - 'Content-Type' => $this->contentType, - 'Content-Disposition' => 'attachment; filename="' . $this->title . '.' . $this->ext . '"', - 'Cache-Control' => 'max-age=0', - 'Cache-Control' => 'max-age=1', - 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past - 'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'), - 'Cache-Control' => 'cache, must-revalidate', - 'Pragma' => 'public' - - )); - - // Check if writer isset - if(!$this->writer) - throw new LaravelExcelException('[ERROR] No writer was set.'); - - // Download - $this->writer->save('php://output'); - - // End the script to prevent corrupted xlsx files - exit; + return $this->store($ext, $path, $returnInfo); } /** * Start render of a new spreadsheet * @return [type] [description] */ - public function render() + protected function _render() { // There should be enough sheets to continue rendering if($this->excel->getSheetCount() < 1) @@ -318,8 +333,8 @@ protected function _setStoragePath($path = false) $this->storagePath = rtrim($path, '/'); // Make sure the storage path exists - if(!file_exists($this->storagePath)) - mkdir($this->storagePath, 0777); + if(!$this->filesystem->isWritable($this->storagePath)) + $this->filesystem->makeDirectory($this->storagePath, 0777, true); } /** @@ -357,10 +372,11 @@ public function __call($method, $params) elseif(starts_with($method, 'set')) { $this->_setAttribute($method, $params); + return $this; } + throw new LaravelExcelException('[ERROR] Writer method ['. $method .'] does not exist.'); - return $this; } public function __destruct() From cd008e2ae68b52037cd24d0f3b337aa1058da0bf Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 28 Apr 2014 21:10:03 +0000 Subject: [PATCH 0011/1332] Import through seperate parser --- src/Maatwebsite/Excel/Excel.php | 40 ++- .../Excel/ExcelServiceProvider.php | 15 +- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 283 +++++++++++++++ .../Excel/Readers/LaravelExcelReader.php | 332 ++++++++++++++++++ .../Excel/Writers/LaravelExcelWriter.php | 3 + 5 files changed, 661 insertions(+), 12 deletions(-) create mode 100644 src/Maatwebsite/Excel/Parsers/ExcelParser.php create mode 100644 src/Maatwebsite/Excel/Readers/LaravelExcelReader.php diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 1458599b3..0b2a6a94f 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -13,6 +13,7 @@ use Maatwebsite\Excel\Readers\HTML_reader; use Illuminate\Config\Repository as Config; use Illuminate\Filesystem\Filesystem as File; +use Maatwebsite\Excel\Readers\LaravelExcelReader; use Maatwebsite\Excel\Writers\LaravelExcelWriter; use Maatwebsite\Excel\Parsers\ViewParser; use Maatwebsite\Excel\Exceptions\LaravelExcelException; @@ -104,10 +105,11 @@ class Excel * @param View $view [description] * @param File $file [description] */ - public function __construct(PHPExcel $excel, LaravelExcelWriter $writer, ViewParser $parser, Config $config, View $view, File $file) + public function __construct(PHPExcel $excel, LaravelExcelReader $reader, LaravelExcelWriter $writer, ViewParser $parser, Config $config, View $view, File $file) { // Set Excel dependencies $this->excel = $excel; + $this->reader = $reader; $this->writer = $writer; $this->parser = $parser; @@ -144,6 +146,27 @@ public function create($title) return $this->writer; } + /** + * + * Load an existing file + * + * @param str $file The file we want to load + * @param bool $firstRowAsIndex Do we want to interpret de first row as labels? + * @return $this + * + */ + public function load($file, $firstRowAsIndex = false, $inputEncoding = 'UTF-8') + { + // Inject excel object + $this->reader->injectExcel($this->excel); + + // Start loading + $this->reader->load($file, $firstRowAsIndex, $inputEncoding); + + // Return the reader object + return $this->reader; + } + /** * Batch import * @return [type] [description] @@ -152,7 +175,7 @@ public function batch($files, $callback) { $this->batch = new Batch($files); - // Do the ballback + // Do the callback if($callback instanceof \Closure) call_user_func($callback, $this, $this->batch->getFiles()); @@ -166,7 +189,8 @@ public function batch($files, $callback) public function loadView() { // Deprecated - throw new LaravelExcelException('[ERROR] Only use the loadView() from inside the sheet closure'); + // TODO: make a shareView() method which replaces the old functionality + throw new LaravelExcelException('[Deprecated] Only use the loadView() from inside the sheet closure'); } /** @@ -175,11 +199,11 @@ public function loadView() protected function _setDefaults() { // Set defaults - $this->delimiter = $this->config->get('excel::delimiter', $this->delimiter); - $this->calculate = $this->config->get('excel::calculate', $this->calculate); - $this->ignoreEmpty = $this->config->get('excel::ignoreEmpty', $this->ignoreEmpty); - $this->dateFormat = $this->config->get('excel::date_format', $this->dateFormat); - $this->seperator = $this->config->get('excel::seperator', $this->seperator); + $this->delimiter = $this->config->get('excel::delimiter', $this->delimiter ); + $this->calculate = $this->config->get('excel::calculate', $this->calculate ); + $this->ignoreEmpty = $this->config->get('excel::ignoreEmpty', $this->ignoreEmpty ); + $this->dateFormat = $this->config->get('excel::date_format', $this->dateFormat ); + $this->seperator = $this->config->get('excel::seperator', $this->seperator ); } /** diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index d3c5ab99d..d9d22ed68 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -3,6 +3,7 @@ use Maatwebsite\Excel\Classes\PHPExcel; use Illuminate\Support\ServiceProvider; use Maatwebsite\Excel\Readers\Html; +use Maatwebsite\Excel\Readers\LaravelExcelReader; use Maatwebsite\Excel\Writers\LaravelExcelWriter; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; use Maatwebsite\Excel\Parsers\ViewParser; @@ -69,8 +70,14 @@ protected function bindClasses() */ protected function bindReaders() { - // Bind the PHPExcel class - $this->app['phpexcel.readers.html'] = $this->app->share(function($app) { + + // Bind the laravel excel reader + $this->app['excel.reader'] = $this->app->share(function($app) { + return new LaravelExcelReader($app['files']); + }); + + // Bind the html reader class + $this->app['excel.readers.html'] = $this->app->share(function($app) { return new Html(); }); } @@ -82,7 +89,7 @@ protected function bindReaders() protected function bindParsers() { $this->app['excel.parsers.view'] = $this->app->share(function($app) { - return new ViewParser($app['phpexcel.readers.html']); + return new ViewParser($app['excel.readers.html']); }); } @@ -106,7 +113,7 @@ protected function bindExcel() // Bind the Excel class and inject its dependencies $this->app['excel'] = $this->app->share(function($app) { - return new Excel($app['phpexcel'], $app['excel.writer'], $app['excel.parsers.view'], $app['config'], $app['view'], $app['files']); + return new Excel($app['phpexcel'], $app['excel.reader'], $app['excel.writer'], $app['excel.parsers.view'], $app['config'], $app['view'], $app['files']); }); } diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php new file mode 100644 index 000000000..9bd12040d --- /dev/null +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -0,0 +1,283 @@ +reader = $reader; + $this->excel = $reader->excel; + } + + /** + * + * Parse the file + * + * @return $this + * + */ + public function parseFile() + { + if(!$this->isParsed) + { + // Set worksheet count + $i = 0; + + // Set empty array + $parsed = array(); + + // Loop through the worksheets + foreach($this->excel->getWorksheetIterator() as $this->worksheet) + { + // Set the active worksheet + $this->excel->setActiveSheetIndex($i); + + // Get the worksheet name + $title = $this->excel->getActiveSheet()->getTitle(); + + // Convert to labels + if($this->reader->firstRowAsIndex !== false) + { + // Fetch the labels + $this->indices = $this->getIndices(); + } + + // Get the sheet count + $this->sheetCount = $this->excel->getSheetCount(); + + // If we have more than 1 worksheet, seperate them + if($this->sheetCount > 1) + { + // Parse the rows into seperate worksheets + $parsed[$title] = $this->parseRows(); + } + else + { + // Parse the rows, but neglect the worksheet title + $parsed = $this->parseRows(); + } + + $i++; + + } + + // Limit the result + if($this->reader->limit !== false) + { + $parsed = array_slice($parsed, $this->reader->limit[1], $this->reader->limit[0]); + } + } + + $this->isParsed = true; + + // Return itself + return $parsed; + } + + /** + * + * Get the labels + * + * @return $this + * + */ + protected function getIndices() + { + // Fetch the first row + $this->row = $this->worksheet->getRowIterator(1)->current(); + + // Set empty labels array + $this->indices = array(); + + // Loop through the cells + foreach ($this->row->getCellIterator() as $this->cell) { + + // Set labels + $this->indices[] = Str::slug($this->cell->getValue(), $this->reader->seperator); + } + + // Return the labels + return $this->indices; + } + + /** + * + * Parse the rows + * + * @return $this + * + */ + protected function parseRows() + { + // Set empty parsedRow array + $parsedRow = array(); + + // If the first row is the label, ignore the first row + $ignore = $this->reader->firstRowAsIndex !== false ? 1 : 0; + + // Loop through the rows inside the worksheet + foreach ($this->worksheet->getRowIterator() as $this->row) { + + // Ignore first row (this can be 0 or 1) + if($this->r >= $ignore) + { + // Set the array, always starting with 0, and fill it with parsed cells + $parsedRow[$this->r - $ignore] = $this->parseCells(); + } + + // Count the rows + $this->r++; + + } + + // Return the parsed array + return $parsedRow; + } + + /** + * + * Parse the cells + * + * @return $this + * + */ + protected function parseCells() + { + $i = 0; + $parsedCells = array(); + + // Set the cell iterator + $cellIterator = $this->row->getCellIterator(); + + // Ignore empty cells + $cellIterator->setIterateOnlyExistingCells($this->reader->ignoreEmpty); + + // Foreach cells + foreach ($cellIterator as $this->cell) { + + // Get the cell index + $index = PHPExcel_Cell::columnIndexFromString($this->cell->getColumn()); + + // Check how we need to save the parsed array + if($this->reader->firstRowAsIndex !== false) + { + // Set label index + $index = $this->indices[$i]; + } + + // If the cell is a date time + if(PHPExcel_Shared_Date::isDateTime($this->cell)) + { + // Check if we want to parse the dates + if ($this->reader->formatDates !== false) + { + // Convert excel time to php date object + $value = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue()); + + // Format the date + $value = $value->format($this->reader->dateFormat); + + // Use carbon to parse the time + if($this->reader->useCarbon) + { + $value = Carbon::parse($value)->{$this->reader->carbonMethod}(); + } + } + else + { + // Format the date to a formatted string + $value = (string) PHPExcel_Style_NumberFormat::toFormattedString( + $this->cell->getCalculatedValue(), + $this->cell->getWorksheet()->getParent() + ->getCellXfByIndex($this->cell->getXfIndex()) + ->getNumberFormat() + ->getFormatCode() + ); + } + } + + // Check if we want calculated values or not + elseif($this->reader->calculate !== false) + { + // Get calculated value + $value = $this->cell->getCalculatedValue(); + } + else + { + // Get real value + $value = $this->cell->getValue(); + } + + // Set the value + $parsedCells[$index] = $value; + $i++; + + } + + // Return array with parsed cells + return $parsedCells; + + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php new file mode 100644 index 000000000..03daf9f6f --- /dev/null +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -0,0 +1,332 @@ +filesystem = $filesystem; + } + + /** + * Load a file + * @param [type] $file [description] + * @param boolean $firstRowAsIndex [description] + * @param string $inputEncoding [description] + * @return [type] [description] + */ + public function load($file, $firstRowAsIndex = false, $inputEncoding = 'UTF-8') + { + // init the loading + $this->_init($file, $firstRowAsIndex, $inputEncoding); + + // Load the file + $this->excel = $this->reader->load($this->file); + + // Return itself + return $this; + } + + /** + * + * Parse the file to an array. + * + * @return array $this->parsed The parsed array + * + */ + public function toArray() + { + // Parse the file + $this->_parseFile(); + + return (array) $this->parsed; + } + + /** + * + * Parse the file to an object. + * + * @return obj $this->parsed The parsed object + * + */ + public function toObject() + { + return (object) json_decode(json_encode($this->toArray())); + } + + /** + * + * Dump the parsed file to a readable array + * + * @return array $this->parsed The parsed array + * + */ + public function dump($die = false) + { + echo '
';
+            $die ? dd($this->toArray()) : var_dump($this->toArray());
+        echo '
'; + } + + /** + * Die and dump + * @return [type] [description] + */ + public function dd() + { + return $this->dump(true); + } + + /** + * Init the loading + * @param [type] $file [description] + * @param [type] $firstRowAsIndex [description] + * @param [type] $inputEncoding [description] + * @return [type] [description] + */ + protected function _init($file, $firstRowAsIndex, $inputEncoding) + { + // Set the extension + $this->_setFile($file) + ->setExtension() + ->setTitle() + ->setFirstRowAsIndex($firstRowAsIndex) + ->_setFormat() + ->_setReader(); + + // If csv, set input encoding + if ($this->format === 'CSV') + $this->setInputEncoding($inputEncoding); + } + + /** + * Inject the excel object + * @param [type] $excel [description] + * @return [type] [description] + */ + public function injectExcel($excel) + { + $this->excel = $excel; + $this->_reset(); + } + + /** + * Set the file + * @param [type] $file [description] + */ + protected function _setFile($file) + { + // check if we have a correct path + if(!realpath($file)) + $file = base_path($file); + + $this->file = $file; + return $this; + } + + /** + * Set the spreadsheet title + * @param [type] $title [description] + */ + public function setTitle($title = false) + { + $this->title = $title ? $title : basename($this->file, '.' . $this->ext); + return $this; + } + + /** + * Set extension + * @param [type] $ext [description] + */ + public function setExtension($ext = false) + { + $this->ext = $ext ? $ext: $this->filesystem->extension($this->file); + return $this; + } + + /** + * Set first row as index + */ + public function setFirstRowAsIndex($do = true) + { + // Set first row as label + $this->firstRowAsIndex = $do; + return $this; + } + + /** + * Set the write format + */ + protected function _setFormat() + { + $this->format = PHPExcel_IOFactory::identify($this->file); + return $this; + } + + /** + * Parse the file + * @return [type] [description] + */ + protected function _parseFile() + { + $parser = new ExcelParser($this); + $this->parsed = $parser->parseFile(); + } + + /** + * Set the writer + */ + protected function _setReader() + { + // Init the reader + $this->reader = PHPExcel_IOFactory::createReader($this->format); + return $this; + } + + /** + * Reset the writer + * @return [type] [description] + */ + protected function _reset() + { + $this->excel->disconnectWorksheets(); + } + + /** + * Dynamically call methods + * @param [type] $method [description] + * @param [type] $params [description] + * @return [type] [description] + */ + public function __call($method, $params) + { + // Call a php excel method + if(method_exists($this->excel, $method)) + { + // Call the method from the excel object with the given params + return call_user_func_array(array($this->excel, $method), $params); + } + + // If it's a reader method + elseif(method_exists($this->reader, $method)) + { + // Call the method from the excel object with the given params + return call_user_func_array(array($this->reader, $method), $params); + } + + throw new LaravelExcelException('[ERROR] Reader method ['. $method .'] does not exist.'); + + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 3c901b725..c4667591b 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -329,6 +329,9 @@ protected function _setStoragePath($path = false) // Get the default path $path = $path ? $path : \Config::get('excel::path', base_path($this->storagePath)); + if(!realpath($path)) + $path = base_path($path); + // Trim of slashes, to makes sure we won't add them double $this->storagePath = rtrim($path, '/'); From a8f5184c5ba1804abd2870244cfe5f36b7d9373c Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 28 Apr 2014 22:00:55 +0000 Subject: [PATCH 0012/1332] Switch to collections --- .../Excel/Collections/CellCollection.php | 50 +++++++++++++++++++ .../Excel/Collections/ExcelCollection.php | 5 ++ .../Excel/Collections/RowCollection.php | 3 ++ .../Excel/Collections/SheetCollection.php | 3 ++ src/Maatwebsite/Excel/Parsers/ExcelParser.php | 38 ++++++++------ .../Excel/Readers/LaravelExcelReader.php | 29 ++++++++--- 6 files changed, 107 insertions(+), 21 deletions(-) create mode 100644 src/Maatwebsite/Excel/Collections/CellCollection.php create mode 100644 src/Maatwebsite/Excel/Collections/ExcelCollection.php create mode 100644 src/Maatwebsite/Excel/Collections/RowCollection.php create mode 100644 src/Maatwebsite/Excel/Collections/SheetCollection.php diff --git a/src/Maatwebsite/Excel/Collections/CellCollection.php b/src/Maatwebsite/Excel/Collections/CellCollection.php new file mode 100644 index 000000000..6cac45b8a --- /dev/null +++ b/src/Maatwebsite/Excel/Collections/CellCollection.php @@ -0,0 +1,50 @@ +setItems($items); + } + + /** + * Create a new collection instance if the value isn't one already. + * + * @param mixed $items + * @return \Illuminate\Support\Collection + */ + public static function make($items) + { + if (is_null($items)) return new static; + return new static(is_array($items) ? $items : array($items)); + } + + /** + * Set the items + * @param [type] $items [description] + */ + public function setItems($items) + { + foreach($items as $name => $value) + { + $this->setItem($name, $value); + } + } + + /** + * Set the item + * @param [type] $name [description] + * @param [type] $value [description] + */ + public function setItem($name, $value) + { + $this->{$name} = $value; + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Collections/ExcelCollection.php b/src/Maatwebsite/Excel/Collections/ExcelCollection.php new file mode 100644 index 000000000..26dc4c260 --- /dev/null +++ b/src/Maatwebsite/Excel/Collections/ExcelCollection.php @@ -0,0 +1,5 @@ +isParsed) { // Set worksheet count $i = 0; - // Set empty array - $parsed = array(); - // Loop through the worksheets foreach($this->excel->getWorksheetIterator() as $this->worksheet) { @@ -103,36 +107,40 @@ public function parseFile() $this->indices = $this->getIndices(); } + // Parse the rows + $worksheet = $this->parseRows(); + // Get the sheet count $this->sheetCount = $this->excel->getSheetCount(); - // If we have more than 1 worksheet, seperate them + // If multiple sheets if($this->sheetCount > 1) { - // Parse the rows into seperate worksheets - $parsed[$title] = $this->parseRows(); + // Push every sheet + $workbook->push($worksheet); } else { - // Parse the rows, but neglect the worksheet title - $parsed = $this->parseRows(); + // Ignore the sheet collection + $workbook = $worksheet; + break; } $i++; } - // Limit the result + // // Limit the result if($this->reader->limit !== false) { - $parsed = array_slice($parsed, $this->reader->limit[1], $this->reader->limit[0]); + $workbook = $workbook->take($this->reader->limit); } } $this->isParsed = true; // Return itself - return $parsed; + return $workbook; } /** @@ -171,7 +179,7 @@ protected function getIndices() protected function parseRows() { // Set empty parsedRow array - $parsedRow = array(); + $parsedRows = new RowCollection(); // If the first row is the label, ignore the first row $ignore = $this->reader->firstRowAsIndex !== false ? 1 : 0; @@ -183,7 +191,7 @@ protected function parseRows() if($this->r >= $ignore) { // Set the array, always starting with 0, and fill it with parsed cells - $parsedRow[$this->r - $ignore] = $this->parseCells(); + $parsedRows->push($this->parseCells()); } // Count the rows @@ -192,7 +200,7 @@ protected function parseRows() } // Return the parsed array - return $parsedRow; + return $parsedRows; } /** @@ -276,7 +284,7 @@ protected function parseCells() } // Return array with parsed cells - return $parsedCells; + return CellCollection::make($parsedCells); } diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 03daf9f6f..2ecd83730 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -4,6 +4,7 @@ use Illuminate\Filesystem\Filesystem; use Maatwebsite\Excel\Parsers\ExcelParser; use Maatwebsite\Excel\Exceptions\LaravelExcelException; +use Illuminate\Support\Collection; class LaravelExcelReader { @@ -138,6 +139,25 @@ public function load($file, $firstRowAsIndex = false, $inputEncoding = 'UTF-8') return $this; } + /** + * Return all sheets/rows + * @return [type] [description] + */ + public function all() + { + return $this->get(); + } + + /** + * Get all sheets/rows + * @return [type] [description] + */ + public function get() + { + $this->_parseFile(); + return $this->parsed; + } + /** * * Parse the file to an array. @@ -147,10 +167,7 @@ public function load($file, $firstRowAsIndex = false, $inputEncoding = 'UTF-8') */ public function toArray() { - // Parse the file - $this->_parseFile(); - - return (array) $this->parsed; + return (array) $this->get()->toArray(); } /** @@ -162,7 +179,7 @@ public function toArray() */ public function toObject() { - return (object) json_decode(json_encode($this->toArray())); + return $this->get(); } /** @@ -175,7 +192,7 @@ public function toObject() public function dump($die = false) { echo '
';
-            $die ? dd($this->toArray()) : var_dump($this->toArray());
+            $die ? dd($this->get()) : var_dump($this->get());
         echo '
'; } From 2ba5310ef183f9a6a2c7b72d611af03c9288cd4a Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 28 Apr 2014 22:18:12 +0000 Subject: [PATCH 0013/1332] Better column selecting and result limiting --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 103 +++++++++--------- .../Excel/Readers/LaravelExcelReader.php | 45 ++++++-- 2 files changed, 87 insertions(+), 61 deletions(-) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 65be9cab6..d9fe5c9ba 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -59,6 +59,12 @@ class ExcelParser { */ protected $indices; + /** + * Columns we want to fetch + * @var array + */ + protected $columns = array(); + /** * Row counter * @var integer @@ -81,11 +87,14 @@ public function __construct($reader) * @return $this * */ - public function parseFile() + public function parseFile($columns = array()) { // Init new sheet collection $workbook = new SheetCollection(); + // Set the columns + $this->columns = $columns; + if(!$this->isParsed) { // Set worksheet count @@ -129,12 +138,6 @@ public function parseFile() $i++; } - - // // Limit the result - if($this->reader->limit !== false) - { - $workbook = $workbook->take($this->reader->limit); - } } $this->isParsed = true; @@ -187,16 +190,16 @@ protected function parseRows() // Loop through the rows inside the worksheet foreach ($this->worksheet->getRowIterator() as $this->row) { - // Ignore first row (this can be 0 or 1) + // Limit the results + if($this->reader->limit && $this->r == ($this->reader->limit + 1) ) + break; + + // Ignore first row when needed if($this->r >= $ignore) - { - // Set the array, always starting with 0, and fill it with parsed cells $parsedRows->push($this->parseCells()); - } // Count the rows $this->r++; - } // Return the parsed array @@ -228,57 +231,59 @@ protected function parseCells() $index = PHPExcel_Cell::columnIndexFromString($this->cell->getColumn()); // Check how we need to save the parsed array - if($this->reader->firstRowAsIndex !== false) - { - // Set label index - $index = $this->indices[$i]; - } + $index = $this->reader->firstRowAsIndex !== false ? $this->indices[$i] : $i; - // If the cell is a date time - if(PHPExcel_Shared_Date::isDateTime($this->cell)) + // Check if we want to select this column + if(empty($this->columns) || (!empty($this->columns) && in_array($index, $this->columns) ) ) { - // Check if we want to parse the dates - if ($this->reader->formatDates !== false) + // If the cell is a date time + if(PHPExcel_Shared_Date::isDateTime($this->cell)) { - // Convert excel time to php date object - $value = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue()); + // Check if we want to parse the dates + if ($this->reader->formatDates !== false) + { + // Convert excel time to php date object + $value = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue()); - // Format the date - $value = $value->format($this->reader->dateFormat); + // Format the date + $value = $value->format($this->reader->dateFormat); - // Use carbon to parse the time - if($this->reader->useCarbon) + // Use carbon to parse the time + if($this->reader->useCarbon) + { + $value = Carbon::parse($value)->{$this->reader->carbonMethod}(); + } + } + else { - $value = Carbon::parse($value)->{$this->reader->carbonMethod}(); + // Format the date to a formatted string + $value = (string) PHPExcel_Style_NumberFormat::toFormattedString( + $this->cell->getCalculatedValue(), + $this->cell->getWorksheet()->getParent() + ->getCellXfByIndex($this->cell->getXfIndex()) + ->getNumberFormat() + ->getFormatCode() + ); } } + + // Check if we want calculated values or not + elseif($this->reader->calculate !== false) + { + // Get calculated value + $value = $this->cell->getCalculatedValue(); + } else { - // Format the date to a formatted string - $value = (string) PHPExcel_Style_NumberFormat::toFormattedString( - $this->cell->getCalculatedValue(), - $this->cell->getWorksheet()->getParent() - ->getCellXfByIndex($this->cell->getXfIndex()) - ->getNumberFormat() - ->getFormatCode() - ); + // Get real value + $value = $this->cell->getValue(); } - } - // Check if we want calculated values or not - elseif($this->reader->calculate !== false) - { - // Get calculated value - $value = $this->cell->getCalculatedValue(); - } - else - { - // Get real value - $value = $this->cell->getValue(); + // Set the value + $parsedCells[$index] = $value; + } - // Set the value - $parsedCells[$index] = $value; $i++; } diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 2ecd83730..06de311a0 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -139,6 +139,27 @@ public function load($file, $firstRowAsIndex = false, $inputEncoding = 'UTF-8') return $this; } + /** + * Take x rows + * @param [type] $amount [description] + * @return [type] [description] + */ + public function take($amount) + { + $this->limit = $amount; + return $this; + } + + /** + * Limit the results by x + * @param [type] $amount [description] + * @return [type] [description] + */ + public function limit($amount) + { + return $this->take($amount); + } + /** * Return all sheets/rows * @return [type] [description] @@ -152,9 +173,9 @@ public function all() * Get all sheets/rows * @return [type] [description] */ - public function get() + public function get($columns = array()) { - $this->_parseFile(); + $this->_parseFile($columns); return $this->parsed; } @@ -165,9 +186,9 @@ public function get() * @return array $this->parsed The parsed array * */ - public function toArray() + public function toArray($columns = array()) { - return (array) $this->get()->toArray(); + return (array) $this->get($columns)->toArray(); } /** @@ -177,9 +198,9 @@ public function toArray() * @return obj $this->parsed The parsed object * */ - public function toObject() + public function toObject($columns = array()) { - return $this->get(); + return $this->get($columns); } /** @@ -189,10 +210,10 @@ public function toObject() * @return array $this->parsed The parsed array * */ - public function dump($die = false) + public function dump($columns = array(), $die = false) { echo '
';
-            $die ? dd($this->get()) : var_dump($this->get());
+            $die ? dd($this->get($columns)) : var_dump($this->get($columns));
         echo '
'; } @@ -200,9 +221,9 @@ public function dump($die = false) * Die and dump * @return [type] [description] */ - public function dd() + public function dd($columns = array()) { - return $this->dump(true); + return $this->dump($columns, true); } /** @@ -295,10 +316,10 @@ protected function _setFormat() * Parse the file * @return [type] [description] */ - protected function _parseFile() + protected function _parseFile($columns = array()) { $parser = new ExcelParser($this); - $this->parsed = $parser->parseFile(); + $this->parsed = $parser->parseFile($columns); } /** From 6e6d51d55d809601dc777d2fff4a8684dc3cfc17 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 28 Apr 2014 22:29:17 +0000 Subject: [PATCH 0014/1332] Parse dates by default with carbon, but formatting is optional --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 21 +++++------ .../Excel/Readers/LaravelExcelReader.php | 37 ++++++++++++------- 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index d9fe5c9ba..b00cca2c4 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -239,24 +239,22 @@ protected function parseCells() // If the cell is a date time if(PHPExcel_Shared_Date::isDateTime($this->cell)) { - // Check if we want to parse the dates - if ($this->reader->formatDates !== false) + if($this->reader->formatDates !== false) { // Convert excel time to php date object - $value = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue()); + $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format(false); - // Format the date - $value = $value->format($this->reader->dateFormat); + // Parse with carbon + $date = Carbon::parse($date); + + // Format the date if wanted + if($this->reader->dateFormat) + $value = $date->format($this->reader->dateFormat); - // Use carbon to parse the time - if($this->reader->useCarbon) - { - $value = Carbon::parse($value)->{$this->reader->carbonMethod}(); - } } else { - // Format the date to a formatted string + //Format the date to a formatted string $value = (string) PHPExcel_Style_NumberFormat::toFormattedString( $this->cell->getCalculatedValue(), $this->cell->getWorksheet()->getParent() @@ -265,6 +263,7 @@ protected function parseCells() ->getFormatCode() ); } + } // Check if we want calculated values or not diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 06de311a0..776bfacaa 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -78,7 +78,7 @@ class LaravelExcelReader { * Slug seperator * @var string */ - public $seperator = '-'; + public $seperator = '_'; /** * Ignore empty cells @@ -96,19 +96,7 @@ class LaravelExcelReader { * Default date format * @var string */ - public $dateFormat = 'Y-m-d'; - - /** - * Use carbon to format dates - * @var boolean - */ - public $useCarbon = false; - - /** - * Default carbon method - * @var string - */ - public $carbonMethod = 'toDateTimeString'; + public $dateFormat = false; /** * Construct new writer @@ -303,6 +291,27 @@ public function setFirstRowAsIndex($do = true) return $this; } + /** + * Set the date format + * @param str $format The date format + */ + public function setDateFormat($format) + { + $this->dateFormat = $format; + return $this; + } + + /** + * Enable/disable date formating + * @param bool $boolean True/false + */ + public function formatDates($boolean, $format = false) + { + $this->formatDates = $boolean; + $this->setDateFormat($format); + return $this; + } + /** * Set the write format */ From 5fe54d2a837d78a6c50e6fc1aeb39b1952f4dc0f Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 28 Apr 2014 22:34:50 +0000 Subject: [PATCH 0015/1332] Re-added couple of methods --- .../Excel/Classes/LaravelExcelWorksheet.php | 195 ++++++++++++++++++ .../Excel/Readers/LaravelExcelReader.php | 14 ++ 2 files changed, 209 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 126017278..227429190 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -427,6 +427,201 @@ public function freezeFirstRowAndColumn() return $this; } + /** + * + * Set a range of cell borders + * + * @param string $pane Start and end of the cell (A1:F10) + * @param string $weight Border style (Reference setBorder style list) + * @return $this + * @example ->setBorder('A1:F10','thick') + * + */ + public function setBorder($pane = 'A1', $weight = 'thin') + { + /* + @ ~ Border styles list ~ @ + + PHPExcel_Style_Border::BORDER_NONE = 'none' + PHPExcel_Style_Border::BORDER_DASHDOT = 'dashDot' + PHPExcel_Style_Border::BORDER_DASHDOTDOT = 'dashDotDot' + PHPExcel_Style_Border::BORDER_DASHED = 'dashed' + PHPExcel_Style_Border::BORDER_DOTTED = 'dotted' + PHPExcel_Style_Border::BORDER_DOUBLE = 'double' + PHPExcel_Style_Border::BORDER_HAIR = 'hair' + PHPExcel_Style_Border::BORDER_MEDIUM = 'medium' + PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT = 'mediumDashDot' + PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot' + PHPExcel_Style_Border::BORDER_MEDIUMDASHED = 'mediumDashed' + PHPExcel_Style_Border::BORDER_SLANTDASHDOT = 'slantDashDot' + PHPExcel_Style_Border::BORDER_THICK = 'thick' + PHPExcel_Style_Border::BORDER_THIN = 'thin' + */ + + $weight = $pane == 'A1' ? 'none' : $weight; + + // Set all borders + $this->excel->getStyle($pane) + ->getBorders() + ->getAllBorders() + ->setBorderStyle($weight); + + return $this; + } + + /** + * + * Set all cell borders + * + * @param string $weight Border style (Reference setBorder style list) + * @return $this + * @example Excel::create()->setAllBorder() Must follow the function of create() + * + */ + public function setAllBorder($weight = 'thin') + { + $styleArray = array( + 'borders' => array( + 'allborders' => array( + 'style' => $weight + ) + ) + ); + + // Apply the style + $this->excel->getDefaultStyle() + ->applyFromArray($styleArray); + + return $this; + } + + /** + * + * Set the cell format of the column + * + * @return $this + * @param array $formats An array of cells you want to format columns + * + * @author xiehai + * @example ->setColumnFormat(array( + * 'B' => '0', + * 'D' => '0.00', + * 'F' => '@', + * 'F' => 'yyyy-mm-dd', + * ...... + * ) + * ) + * @uses This method can only be used before the with() method + * + */ + + /* + * @ ~ The Format list ~ @ + * + PHPExcel_Style_NumberFormat::FORMAT_GENERAL = 'General' + PHPExcel_Style_NumberFormat::FORMAT_TEXT = '@' + PHPExcel_Style_NumberFormat::FORMAT_NUMBER = '0' + PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00 = '0.00' + PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00' + PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-' + PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE = '0%' + PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00 = '0.00%' + PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd' + PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD = 'yy-mm-dd' + PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY = 'dd/mm/yy' + PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH = 'd/m/y' + PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS = 'd-m-y' + PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS = 'd-m' + PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS = 'm-y' + PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14 = 'mm-dd-yy' + PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15 = 'd-mmm-yy' + PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16 = 'd-mmm' + PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17 = 'mmm-yy' + PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22 = 'm/d/yy h:mm' + PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME = 'd/m/y h:mm' + PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1 = 'h:mm AM/PM' + PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM' + PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3 = 'h:mm' + PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4 = 'h:mm:ss' + PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5 = 'mm:ss' + PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6 = 'h:mm:ss' + PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7 = 'i:s.S' + PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8 = 'h:mm:ss;@' + PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@' + PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-' + PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD = '$#,##0_-' + PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-' + */ + public function setColumnFormat(Array $formats){ + + // Loop through the columns + foreach ($formats as $column => $format) { + + // Change the format for a specific cell or range + $this->excel->getStyle($column) + ->getNumberFormat() + ->setFormatCode($format); + } + + return $this; + } + + /** + * + * Set the cell width of the columns + * + * @return $this + * @param array $pane An array of column widths + * + * @author xiehai + * @example ->setColumnWidth(array( + * 'A' => '10', + * 'B' => '22', + * 'F' => '8', + * 'N' => '13', + * ...... + * ) + * ) + * + */ + public function setColumnWidth(Array $pane) + { + foreach ($pane as $column => $width) { + $this->excel->getColumnDimension($column)->setWidth($width); + } + + return $this; + } + + /** + * + * Set the columns you want to merge + * + * @return $this + * @param array $mergeColumn An array of columns you want to merge + * + * @author xiehai + * @example $mergeColumn = array( + * 'columns' => array('A','B','C','D'), + * 'rows' => array( + * array(2,3), + * array(5,11), + * ..... + * ) + * ); + * + */ + public function setMergeColumn(Array $mergeColumn) + { + foreach ($mergeColumn['columns'] as $column) { + foreach ($mergeColumn['rows'] as $row) { + $this->mergeCells($column.$row[0].":".$column.$row[1]); + } + } + + return $this; + } + /** * Get the sheet index * @return [type] [description] diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 776bfacaa..d0ec69a64 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -312,6 +312,20 @@ public function formatDates($boolean, $format = false) return $this; } + /** + * + * Set default calculate + * + * @param bool $do Calculate yes or no + * @return $this + * + */ + public function calculate($do = true) + { + $this->calculate = $do; + return $this; + } + /** * Set the write format */ From cc3f0e30b7b9f4709c3985d9fa51b842ddcee9d6 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 28 Apr 2014 23:42:43 +0000 Subject: [PATCH 0016/1332] Excel style fixes --- .../Excel/Classes/LaravelExcelWorksheet.php | 58 +++++++------------ src/Maatwebsite/Excel/Classes/PHPExcel.php | 31 ++++------ src/Maatwebsite/Excel/Parsers/ViewParser.php | 2 +- .../Excel/Writers/LaravelExcelWriter.php | 13 +++-- 4 files changed, 41 insertions(+), 63 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 227429190..2bd79af9c 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -2,6 +2,7 @@ use \PHPExcel_Worksheet; use Maatwebsite\Excel\Parsers\ViewParser; +use Maatwebsite\Excel\Exceptions\LaravelExcelException; /** * PHPExcel @@ -458,13 +459,11 @@ public function setBorder($pane = 'A1', $weight = 'thin') PHPExcel_Style_Border::BORDER_THIN = 'thin' */ - $weight = $pane == 'A1' ? 'none' : $weight; - // Set all borders - $this->excel->getStyle($pane) - ->getBorders() - ->getAllBorders() - ->setBorderStyle($weight); + $this->getStyle($pane) + ->getBorders() + ->getAllBorders() + ->setBorderStyle($weight); return $this; } @@ -478,7 +477,7 @@ public function setBorder($pane = 'A1', $weight = 'thin') * @example Excel::create()->setAllBorder() Must follow the function of create() * */ - public function setAllBorder($weight = 'thin') + public function setAllBorders($weight = 'thin') { $styleArray = array( 'borders' => array( @@ -489,8 +488,8 @@ public function setAllBorder($weight = 'thin') ); // Apply the style - $this->excel->getDefaultStyle() - ->applyFromArray($styleArray); + $this->getDefaultStyle() + ->applyFromArray($styleArray); return $this; } @@ -558,9 +557,9 @@ public function setColumnFormat(Array $formats){ foreach ($formats as $column => $format) { // Change the format for a specific cell or range - $this->excel->getStyle($column) - ->getNumberFormat() - ->setFormatCode($format); + $this->getStyle($column) + ->getNumberFormat() + ->setFormatCode($format); } return $this; @@ -587,7 +586,7 @@ public function setColumnFormat(Array $formats){ public function setColumnWidth(Array $pane) { foreach ($pane as $column => $width) { - $this->excel->getColumnDimension($column)->setWidth($width); + $this->getColumnDimension($column)->setWidth($width); } return $this; @@ -622,15 +621,6 @@ public function setMergeColumn(Array $mergeColumn) return $this; } - /** - * Get the sheet index - * @return [type] [description] - */ - public function getSheetIndex() - { - return $this->_parent->getActiveSheetIndex(); - } - /** * Get style for cell * @@ -638,13 +628,13 @@ public function getSheetIndex() * @return PHPExcel_Style * @throws PHPExcel_Exception */ - public function getStyle($pCellCoordinate = 'A1') - { - // set cell coordinate as active - $this->setSelectedCells($pCellCoordinate); + // public function getStyle($pCellCoordinate = 'A1') + // { + // // set cell coordinate as active + // $this->setSelectedCells($pCellCoordinate); - return $this->_parent->getCellXfSupervisor(); - } + // return $this->_parent->getCellXfSupervisor(); + // } /** * Dynamically call methods @@ -660,6 +650,7 @@ public function __call($method, $params) { $key = lcfirst(str_replace('with', '', $method)); $this->_addVars($key, reset($params)); + return $this; } // If it's a stter @@ -667,18 +658,11 @@ public function __call($method, $params) { // set the attribute $this->_setAttributes($method, $params); + return $this; } - return $this; + throw new LaravelExcelException('[ERROR] Laravel Worksheet method ['. $method .'] does not exist.'); } - /** - * Reset data on class destruct - */ - public function __destruct() - { - $this->data = array(); - $this->_parent->_cellXfCollection = array(); - } } diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index b78f87092..e2bb6f850 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -65,6 +65,8 @@ class PHPExcel extends PHPOffice_PHPExcel */ public $mergeData; + public $_workSheetCollection = array(); + /** * Allowed autofill properties * @var array @@ -73,17 +75,18 @@ class PHPExcel extends PHPOffice_PHPExcel 'creator', 'lastModifiedBy', 'title', 'description', 'subject', 'keywords', 'category', 'manager', 'company' ); - /** - * Create a new PHPExcel with one Worksheet + /** + * Create sheet and add it to this workbook + * + * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) + * @return PHPExcel_Worksheet + * @throws PHPExcel_Exception */ - public function __construct() + public function createSheet($iSheetIndex = NULL, $title = false) { - parent::__construct(); - - // Lets inject our custom Worksheet - $this->_workSheetCollection = array(); - $this->_workSheetCollection[] = new LaravelExcelWorksheet($this); - + $newSheet = new LaravelExcelWorksheet($this, $title); + $this->addSheet($newSheet, $iSheetIndex); + return $newSheet; } /** @@ -107,14 +110,4 @@ public function setDefaultProperties($custom) } } - /** - * Get active sheet - * - * @return PHPExcel_Worksheet - */ - public function getActiveSheet() - { - return $this->_workSheetCollection[$this->_activeSheetIndex]; - } - } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Parsers/ViewParser.php b/src/Maatwebsite/Excel/Parsers/ViewParser.php index 06b5f140a..d783dd7d5 100644 --- a/src/Maatwebsite/Excel/Parsers/ViewParser.php +++ b/src/Maatwebsite/Excel/Parsers/ViewParser.php @@ -50,7 +50,7 @@ public function parse($sheet) */ protected function _loadHTML($sheet, $html) { - return $this->reader->load($html, true, $sheet)->getActiveSheet(); + return $this->reader->load($html, true, $sheet); } /** diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index c4667591b..0b1fe4b29 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -97,7 +97,7 @@ public function setTitle($title) public function sheet($title, $callback = false) { // Clone the active sheet - $this->sheet = clone $this->excel->getActiveSheet(); + $this->sheet = $this->excel->createSheet(null, $title); // Set the sheet title $this->sheet->setTitle($title); @@ -110,12 +110,13 @@ public function sheet($title, $callback = false) // Do the ballback if($callback instanceof \Closure) - call_user_func($callback, $this->sheet); + call_user_func($callback, $this->sheet); - $this->excel->addSheet($this->sheet->parsed()); + $this->sheet->parsed(); // Count sheets $this->sheetCount++; + return $this; } @@ -237,7 +238,7 @@ public function save($ext = 'xls', $path = false, $returnInfo = false) protected function _render() { // There should be enough sheets to continue rendering - if($this->excel->getSheetCount() < 1) + if($this->excel->getSheetCount() < 0) throw new LaravelExcelException('[ERROR] Aborting spreadsheet render: no sheets were created.'); // Set the format @@ -365,10 +366,10 @@ public function __call($method, $params) } // Call a php excel sheet method - elseif(method_exists($this->excel->getSheet($this->sheetCount), $method)) + elseif(method_exists($this->excel->getActiveSheet(), $method)) { // Call the method from the excel object with the given params - return call_user_func_array(array($this->excel->getSheet($this->sheetCount), $method), $params); + return call_user_func_array(array($this->excel->getActiveSheet(), $method), $params); } // If the dynamic call starts with "with", add the var to the data array From 812b6bd6ea24ef396da190567a4470c624ba95fb Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 29 Apr 2014 19:48:29 +0000 Subject: [PATCH 0017/1332] Batch Uploader --- src/Maatwebsite/Excel/Excel.php | 14 +++-------- .../Excel/Readers/BatchUploader.php | 25 ++++++++++++++++++- .../Excel/Readers/LaravelExcelReader.php | 10 ++++++++ 3 files changed, 38 insertions(+), 11 deletions(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 0b2a6a94f..b25373396 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -1,5 +1,6 @@ - * @contributors Maatwebsite, mewben, hicode, lollypopgr, floptwo, jonwhittlestone, BoHolm */ class Excel @@ -155,7 +155,7 @@ public function create($title) * @return $this * */ - public function load($file, $firstRowAsIndex = false, $inputEncoding = 'UTF-8') + public function load($file, $firstRowAsIndex = true, $inputEncoding = 'UTF-8') { // Inject excel object $this->reader->injectExcel($this->excel); @@ -171,15 +171,9 @@ public function load($file, $firstRowAsIndex = false, $inputEncoding = 'UTF-8') * Batch import * @return [type] [description] */ - public function batch($files, $callback) + public function batch($files, Closure $callback) { - $this->batch = new Batch($files); - - // Do the callback - if($callback instanceof \Closure) - call_user_func($callback, $this, $this->batch->getFiles()); - - return $this; + return new Batch($this, $files, $callback); } /** diff --git a/src/Maatwebsite/Excel/Readers/BatchUploader.php b/src/Maatwebsite/Excel/Readers/BatchUploader.php index 6adc26900..181896132 100644 --- a/src/Maatwebsite/Excel/Readers/BatchUploader.php +++ b/src/Maatwebsite/Excel/Readers/BatchUploader.php @@ -1,9 +1,17 @@ excel = $excel; + // Set files $this->_setFiles($files); + + // Do the callback + if($callback instanceof Closure) + { + foreach($this->getFiles() as $file) + { + $excel = $this->excel->load($file); + call_user_func($callback, $excel, $file); + } + } + + return $this->excel; } /** diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index d0ec69a64..de2862d97 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -167,6 +167,16 @@ public function get($columns = array()) return $this->parsed; } + /** + * Each + * @param [type] $callback [description] + * @return [type] [description] + */ + public function each($callback) + { + return $this->get()->each($callback); + } + /** * * Parse the file to an array. From 010228120551c7389d691e10c8d709ee76a9da0b Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 29 Apr 2014 20:32:18 +0000 Subject: [PATCH 0018/1332] Share views throughout different sheets and switch views inside the sheet closure, fixes issue #70 and #68 --- .../Excel/Classes/LaravelExcelWorksheet.php | 13 +++- src/Maatwebsite/Excel/Excel.php | 19 ++++-- src/Maatwebsite/Excel/Parsers/ViewParser.php | 11 ++-- .../Excel/Writers/LaravelExcelWriter.php | 65 +++++++++++++++++-- 4 files changed, 93 insertions(+), 15 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 2bd79af9c..eda5fbd16 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -134,7 +134,7 @@ public function loadView($view, $data = array(), $mergeData = array()) { // Init the parser if(!$this->parser) - $this->parser = app('excel.parsers.view'); + $this->setParser(); $this->parser->setView($view); $this->parser->setData($data); @@ -143,6 +143,14 @@ public function loadView($view, $data = array(), $mergeData = array()) return $this; } + /** + * Set the parser + */ + public function setParser($parser = false) + { + return $this->parser = $parser ? $parser : app('excel.parsers.view'); + } + /** * Get the view * @return [type] [description] @@ -176,6 +184,7 @@ public function with($key, $value = false) { // Add the vars $this->_addVars($key, $value); + return $this; } /** @@ -193,7 +202,7 @@ protected function _addVars($key, $value = false) // Create excel from array without a view if(!$this->parser) - $this->fromArray($this->data); + return $this->fromArray($this->data); } // Add seperate values diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index b25373396..89c8bdb9e 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -177,14 +177,23 @@ public function batch($files, Closure $callback) } /** - * Load a view + * Create a new file and share a view + * [NOT RECOMMENDED TO USE; ONLY FOR BACKWARDS COMPATABILITY] * @return [type] [description] */ - public function loadView() + public function shareView($view, $data = array(), $mergeData = array()) { - // Deprecated - // TODO: make a shareView() method which replaces the old functionality - throw new LaravelExcelException('[Deprecated] Only use the loadView() from inside the sheet closure'); + return $this->create('New file')->shareView($view, $data, $mergeData); + } + + /** + * Create a new file and load a view + * [NOT RECOMMENDED TO USE; ONLY FOR BACKWARDS COMPATABILITY] + * @return [type] [description] + */ + public function loadView($view, $data = array(), $mergeData = array()) + { + return $this->shareView($view, $data, $mergeData); } /** diff --git a/src/Maatwebsite/Excel/Parsers/ViewParser.php b/src/Maatwebsite/Excel/Parsers/ViewParser.php index d783dd7d5..5c0fd3c82 100644 --- a/src/Maatwebsite/Excel/Parsers/ViewParser.php +++ b/src/Maatwebsite/Excel/Parsers/ViewParser.php @@ -57,9 +57,10 @@ protected function _loadHTML($sheet, $html) * Set the view * @param [type] $view [description] */ - public function setView($view) + public function setView($view = false) { - $this->view = $view; + if($view) + $this->view = $view; } /** @@ -68,7 +69,8 @@ public function setView($view) */ public function setData($data = array()) { - $this->data = array_merge($this->data, $data); + if(!empty($data)) + $this->data = array_merge($this->data, $data); } /** @@ -77,7 +79,8 @@ public function setData($data = array()) */ public function setMergeData($mergeData = array()) { - $this->mergeData = array_merge($this->mergeData, $mergeData); + if(!empty($mergeData)) + $this->mergeData = array_merge($this->mergeData, $mergeData); } } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 0b1fe4b29..8337145e7 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -32,6 +32,12 @@ class LaravelExcelWriter { */ public $writer; + /** + * Parser + * @var [type] + */ + public $parser; + /** * Default extension * @var string @@ -62,6 +68,24 @@ class LaravelExcelWriter { */ protected $sheetCount = -1; + /** + * View + * @var [type] + */ + protected $view; + + /** + * Data + * @var [type] + */ + protected $data = array(); + + /** + * Merge data + * @var array + */ + protected $mergeData = array(); + /** * Construct new writer * @param Response $response [description] @@ -88,6 +112,32 @@ public function setTitle($title) $this->title = $title; } + /** + * Share a view with all sheets + * @return [type] [description] + */ + public function shareView($view, $data = array(), $mergeData = array()) + { + // Init the parser + if(!$this->parser) + $this->parser = app('excel.parsers.view'); + + $this->parser->setView($view); + $this->parser->setData($data); + $this->parser->setMergeData($mergeData); + + return $this; + } + + /** + * Load the view + * @return [type] [description] + */ + public function loadView($view, $data = array(), $mergeData = array()) + { + return $this->shareView($view, $data, $mergeData); + } + /** * Create a new sheet * @param [type] $title [description] @@ -99,6 +149,10 @@ public function sheet($title, $callback = false) // Clone the active sheet $this->sheet = $this->excel->createSheet(null, $title); + // If a parser was set, inject it + if($this->parser) + $this->sheet->setParser($this->parser); + // Set the sheet title $this->sheet->setTitle($title); @@ -112,6 +166,7 @@ public function sheet($title, $callback = false) if($callback instanceof \Closure) call_user_func($callback, $this->sheet); + // Parse the sheet $this->sheet->parsed(); // Count sheets @@ -121,14 +176,15 @@ public function sheet($title, $callback = false) } /** - * Add data - * @param [type] $array [description] - * @return [type] [description] + * Set data for the current sheet + * @param [type] $keys [description] + * @param boolean $value [description] + * @return [type] [description] */ public function with($array) { + // Add the vars $this->fromArray($array); - return $this; } /** @@ -358,6 +414,7 @@ protected function _reset() */ public function __call($method, $params) { + // Call a php excel method if(method_exists($this->excel, $method)) { From 1eed7e26dc773dd363771c3500d6bf9238a2047e Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 29 Apr 2014 20:35:55 +0000 Subject: [PATCH 0019/1332] Unset view inside sheet closure --- .../Excel/Classes/LaravelExcelWorksheet.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index eda5fbd16..59379c6d3 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -143,6 +143,16 @@ public function loadView($view, $data = array(), $mergeData = array()) return $this; } + /** + * Unset the view + * @return [type] [description] + */ + public function unsetView() + { + $this->parser = null; + return $this; + } + /** * Set the parser */ From fca00357146691903a5af60833031a82170b41a2 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 29 Apr 2014 21:58:05 +0000 Subject: [PATCH 0020/1332] CSS Stylesheet parser for views export, fixes issue #56 --- src/Maatwebsite/Excel/Parsers/CssParser.php | 249 +++++++++++ src/Maatwebsite/Excel/Readers/HtmlReader.php | 416 ++++++++++++------- 2 files changed, 509 insertions(+), 156 deletions(-) create mode 100644 src/Maatwebsite/Excel/Parsers/CssParser.php diff --git a/src/Maatwebsite/Excel/Parsers/CssParser.php b/src/Maatwebsite/Excel/Parsers/CssParser.php new file mode 100644 index 000000000..7a22dd1cc --- /dev/null +++ b/src/Maatwebsite/Excel/Parsers/CssParser.php @@ -0,0 +1,249 @@ +dom = $dom; + $this->findStyleSheets()->parse(); + } + + /** + * Lookup the class or id + * @param [type] $type [description] + * @param [type] $name [description] + * @return [type] [description] + */ + public function lookup($type, $name) + { + switch($type) + { + case 'id': + $name = '#' . $name; + break; + + case 'class': + $name = '.' . $name; + break; + } + + // Get the css + $results = $this->toArray(); + + // Return the css if known + if(isset($results[$name])) + return $results[$name]; + + return array(); + } + + /** + * Return array with CSS attributes + * @return [type] [description] + */ + public function toArray() + { + return $this->results; + } + + /** + * Find the stylesheets inside the view + * @return [type] [description] + */ + protected function findStyleSheets() + { + // Import the dom + $this->importDom(); + + // Get all stylesheet tags + $tags = $this->getStyleSheetTags(); + + foreach($tags as $node) + { + $this->links[] = $this->getCleanStyleSheetLink($node); + } + + // We don't need duplicate css files + $this->links = array_unique($this->links); + return $this; + + } + + /** + * Parse the links to css + * @return [type] [description] + */ + protected function parse() + { + foreach($this->links as $link) + { + $css = $this->getCssFromLink($link); + $this->breakCSSToPHP($css); + } + } + + /** + * Break CSS into a PHP array + * @param [type] $css [description] + * @return [type] [description] + */ + protected function breakCSSToPHP($css) + { + $results = array(); + + preg_match_all($this->matcher, $css, $matches); + + foreach($matches[0] as $i => $original) + { + if(!starts_with($original, '@')) // ignore attributes starting with @ (like @import) + $this->breakIntoAttributes($i, $matches); + } + } + + /** + * Break css into attributes + * @return [type] [description] + */ + protected function breakIntoAttributes($i, $matches) + { + // Seperate attributes + $attributes = explode(';', $matches[2][$i]); + + foreach($attributes as $attribute) + { + $this->breakIntoProperties($attribute, $i, $matches); + } + + } + + /** + * Break into css properties + * @return [type] [description] + */ + protected function breakIntoProperties($attribute, $i, $matches) + { + if (strlen(trim($attribute)) > 0 ) // for missing semicolon on last element, which is legal + { + // List properties with name and value + list($name, $value) = explode(':', $attribute); + $this->results[$matches[1][$i]][trim($name)] = $this->cleanValue($value); + } + } + + /** + * Return a clean value + * @param [type] $value [description] + * @return [type] [description] + */ + protected function cleanValue($value) + { + $value = trim($value); + $value = str_replace('!important', '', $value); + return trim($value); + } + + /** + * Import the dom + * @return [type] [description] + */ + protected function importDom() + { + return $this->xml = simplexml_import_dom($this->dom); + } + + /** + * Get all stylesheet tags + * @return [type] [description] + */ + protected function getStyleSheetTags() + { + return $this->xml->xpath('//link[@rel="stylesheet"]'); + } + + /** + * Get the clean link to the stylesheet + * @param [type] $node [description] + * @return [type] [description] + */ + protected function getCleanStyleSheetLink($node) + { + // Get the link + $link = $node->attributes()->href; + + if (substr($link, 0, 4) != 'http') + { + if (substr($link, 0, 1) == '/') { + $link = $this->getUrlScheme() . '://' . $link; + } else { + $link = $this->getUrlScheme() . '://' . dirname($this->getUrlScheme()) . '/' . $link; + } + } + + return $link; + } + + /** + * Get the URL scheme + * @return [type] [description] + */ + protected function getUrlScheme() + { + if(!$this->scheme) + $this->scheme = parse_url(/service/url::getScheme()); + + return $this->scheme; + } + + /** + * Get css from link + * @param [type] $link [description] + * @return [type] [description] + */ + protected function getCssFromLink($link) + { + return file_get_contents($link); + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 4f8a4550a..a5a4dbbba 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -35,6 +35,7 @@ use \PHPExcel_Style_Fill; use \PHPExcel_Style_Font; use \PHPExcel_Style_Alignment; +use Maatwebsite\Excel\Parsers\CssParser; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; class Html extends \PHPExcel_Reader_HTML @@ -210,10 +211,12 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, throw new \PHPExcel_Reader_Exception('Failed to load ',$pFilename,' as a DOM Document'); } + // Parse css + $this->css = new CssParser($dom); + // Discard white space $dom->preserveWhiteSpace = true; - $row = 0; $column = 'A'; $content = ''; @@ -243,6 +246,7 @@ public function autosizeColumn($sheet) } private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, &$cellContent){ + foreach($element->childNodes as $child){ if ($child instanceof \DOMText) { $domText = preg_replace('/\s+/',' ',trim($child->nodeValue)); @@ -287,6 +291,14 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, $this->parseValign($sheet, $column, $row, $attribute->value); break; + case 'class': + $this->styleByClass($sheet, $column, $row, $attribute->value); + break; + + case 'id': + $this->styleById($sheet, $column, $row, $attribute->value); + break; + } @@ -550,6 +562,55 @@ protected function _processHeadings($child, $sheet, $row, $column, $cellContent) return $sheet; } + /** + * Style the element by class + * @param [type] $sheet [description] + * @param [type] $column [description] + * @param [type] $row [description] + * @param [type] $class [description] + * @return [type] [description] + */ + protected function styleByClass($sheet, $column, $row, $class) + { + // If the class has a whitespace + // break into multiple classes + if(str_contains($class, ' ')) + { + $classes = explode(' ', $class); + foreach($classes as $class) + { + return $this->styleByClass($sheet, $column, $row, $class); + } + } + + // Lookup the css + $styles = $this->css->lookup('class', $class); + + // Loop through the styles + foreach($styles as $name => $value) + { + $this->parseCssProperties($sheet, $column, $row, $name, $value); + } + } + + /** + * Style the element by class + * @param [type] $sheet [description] + * @param [type] $column [description] + * @param [type] $row [description] + * @param [type] $class [description] + * @return [type] [description] + */ + protected function styleById($sheet, $column, $row, $class) + { + $styles = $this->css->lookup('id', $class); + + foreach($styles as $name => $value) + { + $this->parseCssProperties($sheet, $column, $row, $name, $value); + } + } + /** * Parse colspans * @param [type] $sheet [description] @@ -685,210 +746,253 @@ protected function parseInlineStyles($sheet, $column, $row, $styleTag) { // Seperate the different styles $styles = explode(';', $styleTag); + + $this->parseCssAttributes($sheet, $column, $row, $styles); + } + + /** + * Parse the styles + * @param [type] $sheet [description] + * @param [type] $column [description] + * @param [type] $row [description] + * @param [type] $styles [description] + * @return [type] [description] + */ + protected function parseCssAttributes($sheet, $column, $row, $styles = array()) + { foreach($styles as $tag) { $style = explode(':', $tag); $name = trim(reset($style)); $value = trim(end($style)); - $cells = $sheet->getStyle($column.$row); + $this->parseCssProperties($sheet, $column, $row, $name, $value); + } + } - switch($name) - { + /** + * Parse CSS + * @param [type] $sheet [description] + * @param [type] $column [description] + * @param [type] $row [description] + * @param [type] $name [description] + * @param [type] $value [description] + * @return [type] [description] + */ + protected function parseCssProperties($sheet, $column, $row, $name, $value) + { + $cells = $sheet->getStyle($column.$row); + switch($name) + { - // BACKGROUND - case 'background': - $value = str_replace('#', '', $value); + // BACKGROUND + case 'background': + $value = $this->getColor($value); - $cells->applyFromArray( - array( - 'fill' => array( - 'type' => PHPExcel_Style_Fill::FILL_SOLID, - 'color' => array ('rgb' => $value) - ) + $cells->applyFromArray( + array( + 'fill' => array( + 'type' => PHPExcel_Style_Fill::FILL_SOLID, + 'color' => array ('rgb' => $value) ) - ); - break; + ) + ); + break; - // TEXT COLOR - case 'color': - $value = str_replace('#', '', $value); - $cells->getFont()->getColor()->applyFromArray( - array('rgb' => $value) - ); - break; - - // FONT SIZE - case 'font-size': - $cells->getFont()->setSize($value); - break; - - // FONT WEIGHT - case 'font-weight': - if($value == 'bold' || $value >= 500) - $cells->getFont()->setBold(true); - break; - - // FONT STYLE - case 'font-style': - if($value == 'italic') - $cells->getFont()->setItalic(true); - break; - - // FONT FACE - case 'font-family': - $cells->getFont()->applyFromArray( - array('name' => $value) - ); - break; - - // TEXT DECORATION - case 'text-decoration': - switch($value) - { - case 'underline': - $cells->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); - break; + // TEXT COLOR + case 'color': + $value = $this->getColor($value); + $cells->getFont()->getColor()->applyFromArray( + array('rgb' => $value) + ); + break; - case 'line-through': - $cells->getFont()->setStrikethrough(true); - break; - } - break; + // FONT SIZE + case 'font-size': + $cells->getFont()->setSize($value); + break; - case 'text-align': + // FONT WEIGHT + case 'font-weight': + if($value == 'bold' || $value >= 500) + $cells->getFont()->setBold(true); + break; - $horizontal = false; + // FONT STYLE + case 'font-style': + if($value == 'italic') + $cells->getFont()->setItalic(true); + break; - switch($value) - { - case 'center': - $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_CENTER; - break; + // FONT FACE + case 'font-family': + $cells->getFont()->applyFromArray( + array('name' => $value) + ); + break; - case 'left': - $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_LEFT; - break; + // TEXT DECORATION + case 'text-decoration': + switch($value) + { + case 'underline': + $cells->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + break; - case 'right': - $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_RIGHT; - break; + case 'line-through': + $cells->getFont()->setStrikethrough(true); + break; + } + break; - case 'justify': - $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY; - break; - } + case 'text-align': - if($horizontal) - $cells->getAlignment()->applyFromArray( - array('horizontal' => $horizontal) - ); + $horizontal = false; - break; + switch($value) + { + case 'center': + $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_CENTER; + break; - case 'vertical-align': + case 'left': + $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_LEFT; + break; - $vertical = false; + case 'right': + $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_RIGHT; + break; - switch($value) - { - case 'top': - $vertical = PHPExcel_Style_Alignment::VERTICAL_TOP; - break; + case 'justify': + $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY; + break; + } - case 'middle': - $vertical = PHPExcel_Style_Alignment::VERTICAL_CENTER; - break; + if($horizontal) + $cells->getAlignment()->applyFromArray( + array('horizontal' => $horizontal) + ); - case 'bottom': - $vertical = PHPExcel_Style_Alignment::VERTICAL_BOTTOM; - break; + break; - case 'justify': - $vertical = PHPExcel_Style_Alignment::VERTICAL_JUSTIFY; - break; + case 'vertical-align': - } + $vertical = false; - if($vertical) - $cells->getAlignment()->applyFromArray( - array('vertical' => $vertical) - ); - break; - - case 'borders': - $borders = explode(' ', $value); - $style = $borders[1]; - $color = end($borders); - $color = str_replace('#', '', $color); - $borderStyle = $this->borderStyle($style); - - $cells->getBorders()->applyFromArray( - array( 'allborders' => array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color ) ) ) - ); - break; + switch($value) + { + case 'top': + $vertical = PHPExcel_Style_Alignment::VERTICAL_TOP; + break; - case 'border-top': - $borders = explode(' ', $value); - $style = $borders[1]; - $color = end($borders); - $color = str_replace('#', '', $color); + case 'middle': + $vertical = PHPExcel_Style_Alignment::VERTICAL_CENTER; + break; - $borderStyle = $this->borderStyle($style); + case 'bottom': + $vertical = PHPExcel_Style_Alignment::VERTICAL_BOTTOM; + break; - $cells->getBorders()->getTop()->applyFromArray( - array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) - ); - break; + case 'justify': + $vertical = PHPExcel_Style_Alignment::VERTICAL_JUSTIFY; + break; - case 'border-bottom': - $borders = explode(' ', $value); - $style = $borders[1]; - $color = end($borders); - $color = str_replace('#', '', $color); - $borderStyle = $this->borderStyle($style); + } - $cells->getBorders()->getBottom()->applyFromArray( - array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) + if($vertical) + $cells->getAlignment()->applyFromArray( + array('vertical' => $vertical) ); - break; + break; - case 'border-right': - $borders = explode(' ', $value); - $style = $borders[1]; - $color = end($borders); - $color = str_replace('#', '', $color); - $borderStyle = $this->borderStyle($style); + case 'border': + case 'borders': + $borders = explode(' ', $value); + $style = $borders[1]; + $color = end($borders); + $color = $this->getColor($color); + $borderStyle = $this->borderStyle($style); + + $cells->getBorders()->applyFromArray( + array( 'allborders' => array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color ) ) ) + ); + break; - $cells->getBorders()->getRight()->applyFromArray( - array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) - ); - break; + case 'border-top': + $borders = explode(' ', $value); + $style = $borders[1]; + $color = end($borders); + $color = $this->getColor($color); - case 'border-left': - $borders = explode(' ', $value); - $style = $borders[1]; - $color = end($borders); - $color = str_replace('#', '', $color); - $borderStyle = $this->borderStyle($style); + $borderStyle = $this->borderStyle($style); - $cells->getBorders()->getLeft()->applyFromArray( - array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) - ); - break; + $cells->getBorders()->getTop()->applyFromArray( + array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) + ); + break; - } + case 'border-bottom': + $borders = explode(' ', $value); + $style = $borders[1]; + $color = end($borders); + $color = $this->getColor($color); + $borderStyle = $this->borderStyle($style); + $cells->getBorders()->getBottom()->applyFromArray( + array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) + ); + break; + + case 'border-right': + $borders = explode(' ', $value); + $style = $borders[1]; + $color = end($borders); + $color = $this->getColor($color); + $borderStyle = $this->borderStyle($style); + + $cells->getBorders()->getRight()->applyFromArray( + array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) + ); + break; + + case 'border-left': + $borders = explode(' ', $value); + $style = $borders[1]; + $color = end($borders); + $color = $this->getColor($color); + $borderStyle = $this->borderStyle($style); + + $cells->getBorders()->getLeft()->applyFromArray( + array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) + ); + break; } } + /** + * Get the color + * @param [type] $color [description] + * @return [type] [description] + */ + public function getColor($color) + { + $color = str_replace('#', '', $color); + + // If color is only 3 chars long, mirror it to 6 chars + if(strlen($color) == 3) + $color = $color . $color; + + return $color; + + } + public function borderStyle($style) { switch($style) { case 'solid'; - return PHPExcel_Style_Border::BORDER_DASHDOT; + return PHPExcel_Style_Border::BORDER_THIN; break; case 'dashed': From 5e9423d46872882e8d99e677b6172c697cd36c6c Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 8 May 2014 15:03:06 +0000 Subject: [PATCH 0021/1332] Excel create closure --- src/Maatwebsite/Excel/Excel.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 89c8bdb9e..aa54d3348 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -127,7 +127,7 @@ public function __construct(PHPExcel $excel, LaravelExcelReader $reader, Laravel * @param [type] $title [description] * @return [type] [description] */ - public function create($title) + public function create($title, $callback = false) { // Set the default properties $this->excel->setDefaultProperties(array( @@ -142,6 +142,10 @@ public function create($title) // Set the title $this->writer->setTitle($title); + // Do the ballback + if($callback instanceof Closure) + call_user_func($callback, $this->writer); + // Return the writer object return $this->writer; } From 8e435e50b3c5f4d8e77eadaca110e0d6c2ccc555 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 8 May 2014 19:38:11 +0000 Subject: [PATCH 0022/1332] Typofix --- src/Maatwebsite/Excel/Excel.php | 2 +- src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index aa54d3348..6d96ae6b7 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -142,7 +142,7 @@ public function create($title, $callback = false) // Set the title $this->writer->setTitle($title); - // Do the ballback + // Do the callback if($callback instanceof Closure) call_user_func($callback, $this->writer); diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 8337145e7..e5df3fb78 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -162,7 +162,7 @@ public function sheet($title, $callback = false) // Autosize columns $this->sheet->setAutosize(\Config::get('excel::sheets.autosize', false)); - // Do the ballback + // Do the callback if($callback instanceof \Closure) call_user_func($callback, $this->sheet); From f3e135e1a98d4a95b0f6ea4692a5e25626b9eb92 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 19:51:20 +0000 Subject: [PATCH 0023/1332] load() closure --- src/Maatwebsite/Excel/Excel.php | 9 ++++--- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 15 +++-------- .../Excel/Readers/LaravelExcelReader.php | 27 +++---------------- src/config/export.php | 0 src/config/import.php | 12 +++++++++ src/config/views.php | 0 6 files changed, 25 insertions(+), 38 deletions(-) create mode 100644 src/config/export.php create mode 100644 src/config/import.php create mode 100644 src/config/views.php diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 6d96ae6b7..1006d4189 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -159,13 +159,17 @@ public function create($title, $callback = false) * @return $this * */ - public function load($file, $firstRowAsIndex = true, $inputEncoding = 'UTF-8') + public function load($file, $callback = false) { // Inject excel object $this->reader->injectExcel($this->excel); // Start loading - $this->reader->load($file, $firstRowAsIndex, $inputEncoding); + $this->reader->load($file); + + // Do the callback + if($callback instanceof Closure) + call_user_func($callback, $this->reader); // Return the reader object return $this->reader; @@ -182,7 +186,6 @@ public function batch($files, Closure $callback) /** * Create a new file and share a view - * [NOT RECOMMENDED TO USE; ONLY FOR BACKWARDS COMPATABILITY] * @return [type] [description] */ public function shareView($view, $data = array(), $mergeData = array()) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index b00cca2c4..77137d339 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -109,12 +109,8 @@ public function parseFile($columns = array()) // Get the worksheet name $title = $this->excel->getActiveSheet()->getTitle(); - // Convert to labels - if($this->reader->firstRowAsIndex !== false) - { - // Fetch the labels - $this->indices = $this->getIndices(); - } + // Fetch the labels + $this->indices = $this->getIndices(); // Parse the rows $worksheet = $this->parseRows(); @@ -184,9 +180,6 @@ protected function parseRows() // Set empty parsedRow array $parsedRows = new RowCollection(); - // If the first row is the label, ignore the first row - $ignore = $this->reader->firstRowAsIndex !== false ? 1 : 0; - // Loop through the rows inside the worksheet foreach ($this->worksheet->getRowIterator() as $this->row) { @@ -195,7 +188,7 @@ protected function parseRows() break; // Ignore first row when needed - if($this->r >= $ignore) + if($this->r >= 1) $parsedRows->push($this->parseCells()); // Count the rows @@ -231,7 +224,7 @@ protected function parseCells() $index = PHPExcel_Cell::columnIndexFromString($this->cell->getColumn()); // Check how we need to save the parsed array - $index = $this->reader->firstRowAsIndex !== false ? $this->indices[$i] : $i; + $index = $this->indices[$i]; // Check if we want to select this column if(empty($this->columns) || (!empty($this->columns) && in_array($index, $this->columns) ) ) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index de2862d97..e0087bd71 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -50,12 +50,6 @@ class LaravelExcelReader { */ public $parsed; - /** - * Set first row as indices - * @var boolean - */ - public $firstRowAsIndex = false; - /** * Delimtier * @var [type] @@ -115,10 +109,10 @@ public function __construct(Filesystem $filesystem) * @param string $inputEncoding [description] * @return [type] [description] */ - public function load($file, $firstRowAsIndex = false, $inputEncoding = 'UTF-8') + public function load($file) { // init the loading - $this->_init($file, $firstRowAsIndex, $inputEncoding); + $this->_init($file); // Load the file $this->excel = $this->reader->load($this->file); @@ -231,19 +225,14 @@ public function dd($columns = array()) * @param [type] $inputEncoding [description] * @return [type] [description] */ - protected function _init($file, $firstRowAsIndex, $inputEncoding) + protected function _init($file) { // Set the extension $this->_setFile($file) ->setExtension() ->setTitle() - ->setFirstRowAsIndex($firstRowAsIndex) ->_setFormat() ->_setReader(); - - // If csv, set input encoding - if ($this->format === 'CSV') - $this->setInputEncoding($inputEncoding); } /** @@ -291,16 +280,6 @@ public function setExtension($ext = false) return $this; } - /** - * Set first row as index - */ - public function setFirstRowAsIndex($do = true) - { - // Set first row as label - $this->firstRowAsIndex = $do; - return $this; - } - /** * Set the date format * @param str $format The date format diff --git a/src/config/export.php b/src/config/export.php new file mode 100644 index 000000000..e69de29bb diff --git a/src/config/import.php b/src/config/import.php new file mode 100644 index 000000000..cee86d04c --- /dev/null +++ b/src/config/import.php @@ -0,0 +1,12 @@ + 'UTF-8', + +); \ No newline at end of file diff --git a/src/config/views.php b/src/config/views.php new file mode 100644 index 000000000..e69de29bb From b7aa1988444a7da07962baaf0ebfa01b53a16d34 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 20:35:34 +0000 Subject: [PATCH 0024/1332] Load advanced excel files with a config file --- .../Readers/{BatchUploader.php => Batch.php} | 0 .../Excel/Readers/ConfigReader.php | 152 ++++++++++++++++++ .../Excel/Readers/LaravelExcelReader.php | 12 ++ src/config/import.php | 24 +++ 4 files changed, 188 insertions(+) rename src/Maatwebsite/Excel/Readers/{BatchUploader.php => Batch.php} (100%) create mode 100644 src/Maatwebsite/Excel/Readers/ConfigReader.php diff --git a/src/Maatwebsite/Excel/Readers/BatchUploader.php b/src/Maatwebsite/Excel/Readers/Batch.php similarity index 100% rename from src/Maatwebsite/Excel/Readers/BatchUploader.php rename to src/Maatwebsite/Excel/Readers/Batch.php diff --git a/src/Maatwebsite/Excel/Readers/ConfigReader.php b/src/Maatwebsite/Excel/Readers/ConfigReader.php new file mode 100644 index 000000000..71c8fdb00 --- /dev/null +++ b/src/Maatwebsite/Excel/Readers/ConfigReader.php @@ -0,0 +1,152 @@ +excel = $excel; + + // config name + $this->configName = $config; + + // start + $this->start($callback); + } + + /** + * Start the import + * @param boolean $callback [description] + * @return [type] [description] + */ + public function start($callback = false) + { + // Init a new sheet collection + $this->sheetCollection = new SheetCollection(); + + // Get the sheet names + if($sheets = $this->excel->getSheetNames()) + { + // Loop through the sheets + foreach($sheets as $index => $name) + { + // Set sheet name + $this->sheetName = $name; + + // Set sheet + $this->sheet = $this->excel->setActiveSheetIndex($index); + + // Do the callback + if($callback instanceof Closure) + { + call_user_func($callback, $this); + } + // If no callback, put it inside the sheet collection + else + { + $this->sheetCollection->push(clone $this); + } + } + } + } + + /** + * Get the sheet collection + * @return [type] [description] + */ + public function getSheetCollection() + { + return $this->sheetCollection; + } + + /** + * Get value by index + * @param [type] $field [description] + * @return [type] [description] + */ + protected function valueByIndex($field) + { + $field = snake_case($field); + + if($coordinate = $this->getCoordinateByKey($field)) + { + return $this->getCellValueByCoordinate($coordinate); + } + + return null; + } + + /** + * Return cell value + * @param [type] $coordinate [description] + * @return [type] [description] + */ + protected function getCellValueByCoordinate($coordinate) + { + if($this->sheet) + { + if(str_contains($coordinate, ':')) + { + // We want to get a range of cells + $values = $this->sheet->rangeToArray($coordinate); + return $values; + } + else + { + // We want 1 specific cell + return $this->sheet->getCell($coordinate)->getValue(); + } + } + + return null; + } + + /** + * Get the coordinates from the config file + * @param [type] $field [description] + * @return [type] [description] + */ + protected function getCoordinateByKey($field) + { + return Config::get($this->configName . '.' . $this->sheetName . '.' . $field, false); + } + + public function __get($field) + { + return $this->valueByIndex($field); + } +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index e0087bd71..12ba14c68 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -121,6 +121,18 @@ public function load($file) return $this; } + /** + * Read the file through a config file + * @param [type] $config [description] + * @param boolean $callback [description] + * @return [type] [description] + */ + public function byConfig($config, $callback = false) + { + $config = new ConfigReader($this->excel, $config, $callback); + return $config->getSheetCollection(); + } + /** * Take x rows * @param [type] $amount [description] diff --git a/src/config/import.php b/src/config/import.php index cee86d04c..46309f69e 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -9,4 +9,28 @@ */ 'encoding' => 'UTF-8', + /* + |-------------------------------------------------------------------------- + | Import sheets by config + |-------------------------------------------------------------------------- + */ + 'sheets' => array( + + /* + |-------------------------------------------------------------------------- + | Example sheet + |-------------------------------------------------------------------------- + | + | Example sheet "test" will grab the firstname at cell A2 + | + */ + + 'test' => array( + + 'firstname' => 'A2' + + ) + + ) + ); \ No newline at end of file From e27f480f0aa61d55c7fd392019d99053d5557160 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 20:45:19 +0000 Subject: [PATCH 0025/1332] Set default store behaviour inside config, fixes issue #71 --- src/Maatwebsite/Excel/Excel.php | 1 - src/Maatwebsite/Excel/Parsers/ExcelParser.php | 1 - .../Excel/Writers/LaravelExcelWriter.php | 8 +++- src/config/config.php | 11 ------ src/config/export.php | 37 +++++++++++++++++++ 5 files changed, 43 insertions(+), 15 deletions(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 1006d4189..875897ecd 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -29,7 +29,6 @@ class Excel { - /** * Excel object * @var [type] diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 77137d339..512ddcce5 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -243,7 +243,6 @@ protected function parseCells() // Format the date if wanted if($this->reader->dateFormat) $value = $date->format($this->reader->dateFormat); - } else { diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index e5df3fb78..106835953 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -1,5 +1,6 @@ sheet->setDefaultPageSetup(); // Autosize columns - $this->sheet->setAutosize(\Config::get('excel::sheets.autosize', false)); + $this->sheet->setAutosize(Config::get('excel::sheets.autosize', false)); // Do the callback if($callback instanceof \Closure) @@ -243,6 +244,9 @@ public function download() */ public function store($ext = 'xls', $path = false, $returnInfo = false) { + // Set default return Info + $returnInfo = $returnInfo ? $returnInfo : Config::get('excel::export.store.returnInfo', false); + // Set the storage path $this->_setStoragePath($path); @@ -384,7 +388,7 @@ protected function _setHeaders($headers) protected function _setStoragePath($path = false) { // Get the default path - $path = $path ? $path : \Config::get('excel::path', base_path($this->storagePath)); + $path = $path ? $path : Config::get('excel::export.store.path', base_path($this->storagePath)); if(!realpath($path)) $path = base_path($path); diff --git a/src/config/config.php b/src/config/config.php index 69f061ea3..cf9853016 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -142,15 +142,4 @@ 'date_format' => 'Y-m-d', - /* - |-------------------------------------------------------------------------- - | Path - |-------------------------------------------------------------------------- - | - | The path we want to save excel file to - | - */ - - 'path' => base_path('app/storage/uploads'), - ); diff --git a/src/config/export.php b/src/config/export.php index e69de29bb..b487809e0 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -0,0 +1,37 @@ + array( + + /* + |-------------------------------------------------------------------------- + | Path + |-------------------------------------------------------------------------- + | + | The path we want to save excel file to + | + */ + + 'path' => base_path('app/storage/uploads'), + + /* + |-------------------------------------------------------------------------- + | Return info + |-------------------------------------------------------------------------- + | + | Wether we want to return information about the stored file or not + | + */ + + 'returnInfo' => false + + ) + +); \ No newline at end of file From f59b2bb74b117afac65881230c12d22e825e2877 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 21:03:54 +0000 Subject: [PATCH 0026/1332] Import config value to import first row as heading + noHeading() as disabler --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 9 ++++-- .../Excel/Readers/LaravelExcelReader.php | 32 ++++++++++++++++++- .../Excel/Writers/LaravelExcelWriter.php | 5 +++ src/config/import.php | 11 +++++++ 4 files changed, 53 insertions(+), 4 deletions(-) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 512ddcce5..37ebf3b42 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -110,7 +110,7 @@ public function parseFile($columns = array()) $title = $this->excel->getActiveSheet()->getTitle(); // Fetch the labels - $this->indices = $this->getIndices(); + $this->indices = $this->reader->hasHeading() ? $this->getIndices() : array(); // Parse the rows $worksheet = $this->parseRows(); @@ -180,6 +180,9 @@ protected function parseRows() // Set empty parsedRow array $parsedRows = new RowCollection(); + // Set if we have to ignore rows + $ignore = $this->reader->hasHeading() ? 1 : 0; + // Loop through the rows inside the worksheet foreach ($this->worksheet->getRowIterator() as $this->row) { @@ -188,7 +191,7 @@ protected function parseRows() break; // Ignore first row when needed - if($this->r >= 1) + if($this->r >= $ignore) $parsedRows->push($this->parseCells()); // Count the rows @@ -224,7 +227,7 @@ protected function parseCells() $index = PHPExcel_Cell::columnIndexFromString($this->cell->getColumn()); // Check how we need to save the parsed array - $index = $this->indices[$i]; + $index = $this->reader->hasHeading() ? $this->indices[$i] : $i; // Check if we want to select this column if(empty($this->columns) || (!empty($this->columns) && in_array($index, $this->columns) ) ) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 12ba14c68..1097bf12a 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -1,5 +1,6 @@ formatDates = $boolean; $this->setDateFormat($format); return $this; } + /** + * If the file has a table heading or not + * @param [type] $boolean [description] + * @return [type] [description] + */ + public function noHeading($boolean = true) + { + $this->noHeading = $boolean; + return $this; + } + /** * * Set default calculate @@ -327,6 +345,18 @@ public function calculate($do = true) return $this; } + /** + * Check if the file has een heading + * @return boolean [description] + */ + public function hasHeading() + { + if(!$this->noHeading) + return Config::get('excel::import.heading', true); + + return $this->noHeading ? false : true; + } + /** * Set the write format */ diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 106835953..98ed6cf0e 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -98,6 +98,11 @@ public function __construct(Response $response, FileSystem $filesystem) $this->filesystem = $filesystem; } + /** + * Inject the excel object + * @param [type] $excel [description] + * @return [type] [description] + */ public function injectExcel($excel) { $this->excel = $excel; diff --git a/src/config/import.php b/src/config/import.php index 46309f69e..9f6bad714 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -2,6 +2,17 @@ return array( + /* + |-------------------------------------------------------------------------- + | Has heading + |-------------------------------------------------------------------------- + | + | The sheet has a heading row which we can use as attribute names + | + */ + + 'heading' => true, + /* |-------------------------------------------------------------------------- | Input encoding From 0c38bce432ebd93cae51b20c2a3ad31fefbfe65d Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 21:26:39 +0000 Subject: [PATCH 0027/1332] CSV fixes + set default delimiter inside config && fixes issue #53 --- .../Excel/Collections/CellCollection.php | 3 +- src/Maatwebsite/Excel/Excel.php | 47 --------------- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 +- .../Excel/Readers/LaravelExcelReader.php | 43 +++++++++++++- src/config/config.php | 59 ------------------- src/config/import.php | 57 ++++++++++++++++++ 6 files changed, 102 insertions(+), 109 deletions(-) diff --git a/src/Maatwebsite/Excel/Collections/CellCollection.php b/src/Maatwebsite/Excel/Collections/CellCollection.php index 6cac45b8a..f8aee5fdd 100644 --- a/src/Maatwebsite/Excel/Collections/CellCollection.php +++ b/src/Maatwebsite/Excel/Collections/CellCollection.php @@ -44,7 +44,8 @@ public function setItems($items) */ public function setItem($name, $value) { - $this->{$name} = $value; + if($name) + $this->{$name} = $value ? $value : null; } } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 875897ecd..1fc2bdfee 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -65,37 +65,6 @@ class Excel */ protected $fileSystem; - /** - * Default CSV delimiter - * @var string - */ - protected $delimiter = ','; - - /** - * Calculate formulas - * @var boolean - */ - protected $calculate = true; - - /** - * Ignore empty cells - * @var boolean - */ - protected $ignoreEmpty = true; - - /** - * Default date format - * @var string - */ - protected $dateFormat = 'Y-m-d'; - - /** - * Sheet heading to indices space replacer - * @var string - */ - protected $seperator = '_'; - - /** * Construct Excel * @param PHPExcel $excel [description] @@ -116,9 +85,6 @@ public function __construct(PHPExcel $excel, LaravelExcelReader $reader, Laravel $this->config = $config; $this->viewFactory = $view; $this->fileSystem = $file; - - // Set defaults - $this->_setDefaults(); } /** @@ -202,19 +168,6 @@ public function loadView($view, $data = array(), $mergeData = array()) return $this->shareView($view, $data, $mergeData); } - /** - * Set defaults - */ - protected function _setDefaults() - { - // Set defaults - $this->delimiter = $this->config->get('excel::delimiter', $this->delimiter ); - $this->calculate = $this->config->get('excel::calculate', $this->calculate ); - $this->ignoreEmpty = $this->config->get('excel::ignoreEmpty', $this->ignoreEmpty ); - $this->dateFormat = $this->config->get('excel::date_format', $this->dateFormat ); - $this->seperator = $this->config->get('excel::seperator', $this->seperator ); - } - /** * Dynamically call methods * @param [type] $method [description] diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 37ebf3b42..ff4dd6b54 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -161,7 +161,7 @@ protected function getIndices() foreach ($this->row->getCellIterator() as $this->cell) { // Set labels - $this->indices[] = Str::slug($this->cell->getValue(), $this->reader->seperator); + $this->indices[] = Str::slug($this->cell->getValue(), $this->reader->getSeperator()); } // Return the labels diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 1097bf12a..6e07daba1 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -73,7 +73,7 @@ class LaravelExcelReader { * Slug seperator * @var string */ - public $seperator = '_'; + public $seperator = false; /** * Ignore empty cells @@ -331,6 +331,24 @@ public function noHeading($boolean = true) return $this; } + /** + * Set the cell name word seperator + * @param [type] $seperator [description] + */ + public function setSeperator($seperator) + { + $this->seperator = $seperator; + } + + /** + * Set the delimiter + */ + public function setDelimiter($delimiter) + { + $this->reader->setDelimiter($delimiter); + return $this; + } + /** * * Set default calculate @@ -357,6 +375,18 @@ public function hasHeading() return $this->noHeading ? false : true; } + /** + * Get the seperator + * @return [type] [description] + */ + public function getSeperator() + { + if($this->seperator) + return $this->seperator; + + return Config::get('excel::import.seperator', '_'); + } + /** * Set the write format */ @@ -383,9 +413,20 @@ protected function _setReader() { // Init the reader $this->reader = PHPExcel_IOFactory::createReader($this->format); + $this->_setReaderDefaults(); return $this; } + /** + * Set reader defaults + */ + protected function _setReaderDefaults() + { + // Set CSV delimiter + if($this->format == 'CSV') + $this->reader->setDelimiter(Config::get('excel::import.delimiter', ',')); + } + /** * Reset the writer * @return [type] [description] diff --git a/src/config/config.php b/src/config/config.php index cf9853016..14267f4c8 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -83,63 +83,4 @@ 'creator' => 'Maatwebsite', - /* - |-------------------------------------------------------------------------- - | Delimiter - |-------------------------------------------------------------------------- - | - | The default delimiter which will be used to read out a CSV file - | If you would like to use an other delimiter only one time, - | you can also use the `setDelimiter()` chain. - | - */ - - 'delimiter' => ',', - - /* - |-------------------------------------------------------------------------- - | Slug seperator - |-------------------------------------------------------------------------- - | - | The default seperator for the Str::slug() method. - | If you have problemen with _ being converted to -, you can - | change the seperator to _ here. - | - */ - - 'seperator' => '-', - - /* - |-------------------------------------------------------------------------- - | Calculate - |-------------------------------------------------------------------------- - | - | By default cells with formulas will not be calculated. - | - */ - - 'calculate' => false, - - /* - |-------------------------------------------------------------------------- - | Ignore empty cells - |-------------------------------------------------------------------------- - | - | By default empty cells are not ignored - | - */ - - 'ignoreEmpty' => false, - - /* - |-------------------------------------------------------------------------- - | Date format - |-------------------------------------------------------------------------- - | - | The format dates will be parsed to - | - */ - - 'date_format' => 'Y-m-d', - ); diff --git a/src/config/import.php b/src/config/import.php index 9f6bad714..1e6288624 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -13,6 +13,17 @@ 'heading' => true, + /* + |-------------------------------------------------------------------------- + | Cell name word seperator + |-------------------------------------------------------------------------- + | + | The default seperator which is used for the cell names + | + */ + + 'seperator' => '_', + /* |-------------------------------------------------------------------------- | Input encoding @@ -20,6 +31,52 @@ */ 'encoding' => 'UTF-8', + /* + |-------------------------------------------------------------------------- + | Delimiter + |-------------------------------------------------------------------------- + | + | The default delimiter which will be used to read out a CSV file + | If you would like to use an other delimiter only one time, + | you can also use the `setDelimiter()` chain. + | + */ + + 'delimiter' => ',', + + /* + |-------------------------------------------------------------------------- + | Calculate + |-------------------------------------------------------------------------- + | + | By default cells with formulas will not be calculated. + | + */ + + 'calculate' => true, + + /* + |-------------------------------------------------------------------------- + | Ignore empty cells + |-------------------------------------------------------------------------- + | + | By default empty cells are not ignored + | + */ + + 'ignoreEmpty' => false, + + /* + |-------------------------------------------------------------------------- + | Date format + |-------------------------------------------------------------------------- + | + | The format dates will be parsed to + | + */ + + 'date_format' => 'Y-m-d', + /* |-------------------------------------------------------------------------- | Import sheets by config From bd79ebd7529fbc9a132d5935cec8cc2fea9dd165 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 21:52:48 +0000 Subject: [PATCH 0028/1332] Set names of columns which should be parsed as date (usefull for CSV importing) --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 11 +- .../Excel/Readers/LaravelExcelReader.php | 100 +++++++++++++++++- src/config/import.php | 29 ++++- 3 files changed, 127 insertions(+), 13 deletions(-) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index ff4dd6b54..d7c12e7b9 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -218,7 +218,7 @@ protected function parseCells() $cellIterator = $this->row->getCellIterator(); // Ignore empty cells - $cellIterator->setIterateOnlyExistingCells($this->reader->ignoreEmpty); + $cellIterator->setIterateOnlyExistingCells($this->reader->needsIgnoreEmpty()); // Foreach cells foreach ($cellIterator as $this->cell) { @@ -233,9 +233,9 @@ protected function parseCells() if(empty($this->columns) || (!empty($this->columns) && in_array($index, $this->columns) ) ) { // If the cell is a date time - if(PHPExcel_Shared_Date::isDateTime($this->cell)) + if(PHPExcel_Shared_Date::isDateTime($this->cell) || in_array($index, $this->reader->getDateColumns())) { - if($this->reader->formatDates !== false) + if($this->reader->needsDateFormatting()) { // Convert excel time to php date object $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format(false); @@ -244,8 +244,7 @@ protected function parseCells() $date = Carbon::parse($date); // Format the date if wanted - if($this->reader->dateFormat) - $value = $date->format($this->reader->dateFormat); + $value = $this->reader->getDateFormat() ? $date->format($this->reader->getDateFormat()) : $date; } else { @@ -262,7 +261,7 @@ protected function parseCells() } // Check if we want calculated values or not - elseif($this->reader->calculate !== false) + elseif($this->reader->needsCalculation()) { // Get calculated value $value = $this->cell->getCalculatedValue(); diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 6e07daba1..47dfa641b 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -87,6 +87,12 @@ class LaravelExcelReader { */ public $formatDates = true; + /** + * The date columns + * @var array + */ + public $dateColumns = array(); + /** * If the file has a heading or not * @var boolean @@ -97,7 +103,7 @@ class LaravelExcelReader { * Default date format * @var string */ - public $dateFormat = false; + public $dateFormat; /** * Construct new writer @@ -303,8 +309,9 @@ public function setExtension($ext = false) * Set the date format * @param str $format The date format */ - public function setDateFormat($format) + public function setDateFormat($format = false) { + $this->formatDates = $format ? true : false; $this->dateFormat = $format; return $this; } @@ -320,6 +327,17 @@ public function formatDates($boolean = true, $format = false) return $this; } + /** + * Set the date columns + */ + public function setDateColumns() + { + $this->formatDates = true; + $columns = func_get_args(); + $this->dateColumns = array_merge($this->dateColumns, array_flatten($columns)); + return $this; + } + /** * If the file has a table heading or not * @param [type] $boolean [description] @@ -338,6 +356,7 @@ public function noHeading($boolean = true) public function setSeperator($seperator) { $this->seperator = $seperator; + return $this; } /** @@ -353,13 +372,24 @@ public function setDelimiter($delimiter) * * Set default calculate * - * @param bool $do Calculate yes or no + * @param bool $boolean Calculate yes or no * @return $this * */ - public function calculate($do = true) + public function calculate($boolean = true) { - $this->calculate = $do; + $this->calculate = $boolean; + return $this; + } + + /** + * Ignore empty cells + * @param boolean $boolean [description] + * @return [type] [description] + */ + public function ignoreEmpty($boolean = true) + { + $this->ignoreEmpty = $boolean; return $this; } @@ -387,6 +417,51 @@ public function getSeperator() return Config::get('excel::import.seperator', '_'); } + /** + * Get the dateFormat + * @return [type] [description] + */ + public function getDateFormat() + { + return $this->dateFormat; + } + + /** + * Get the date columns + * @return [type] [description] + */ + public function getDateColumns() + { + return $this->dateColumns; + } + + /** + * Check if we need to calculate the formula inside the cell + * @return [type] [description] + */ + public function needsCalculation() + { + return $this->calculate; + } + + /** + * Check if we need to ingore the empty cells + * @return [type] [description] + */ + public function needsIgnoreEmpty() + { + return $this->ignoreEmpty; + } + + /** + * Check if we need to format the dates + * @return [type] [description] + */ + public function needsDateFormatting() + { + return $this->formatDates ? true : false; + } + /** * Set the write format */ @@ -425,6 +500,21 @@ protected function _setReaderDefaults() // Set CSV delimiter if($this->format == 'CSV') $this->reader->setDelimiter(Config::get('excel::import.delimiter', ',')); + + // Set default calculate + $this->calculate = Config::get('excel::import.calculate', true); + + // Set default for ignoring empty cells + $this->calculate = Config::get('excel::import.ignoreEmpty', true); + + // Set default date format + $this->dateFormat = Config::get('excel::import.dates.format', 'Y-m-d'); + + // Date formatting disabled/enabled + $this->formatDates = Config::get('excel::import.dates.enabled', true); + + // Set default date columns + $this->dateColumns = Config::get('excel::import.dates.columns', array()); } /** diff --git a/src/config/import.php b/src/config/import.php index 1e6288624..d2f8d65ea 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -49,7 +49,7 @@ | Calculate |-------------------------------------------------------------------------- | - | By default cells with formulas will not be calculated. + | By default cells with formulas will be calculated. | */ @@ -75,7 +75,32 @@ | */ - 'date_format' => 'Y-m-d', + 'dates' => array( + + /* + |-------------------------------------------------------------------------- + | Enable/disable date formatting + |-------------------------------------------------------------------------- + */ + 'enabled' => true, + + /* + |-------------------------------------------------------------------------- + | Default date format + |-------------------------------------------------------------------------- + | + | If set to false, a carbon object will return + | + */ + 'format' => false, + + /* + |-------------------------------------------------------------------------- + | Date columns + |-------------------------------------------------------------------------- + */ + 'columns' => array() + ), /* |-------------------------------------------------------------------------- From cfa5c8e19ad48b23e1b8caaf094ec908437aaac2 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 22:15:58 +0000 Subject: [PATCH 0029/1332] Fix for CSV iput encoding, fixes issue #47 --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 ++ src/Maatwebsite/Excel/Readers/LaravelExcelReader.php | 9 +++++++++ src/config/import.php | 1 + 3 files changed, 12 insertions(+) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index d7c12e7b9..0dcae231e 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -1,5 +1,6 @@ cell->getValue(); + $value = iconv(Config::get('excel::import.encoding', 'UTF-8'), 'CP1252', $value); } // Set the value diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 47dfa641b..04a116206 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -39,6 +39,12 @@ class LaravelExcelReader { */ public $ext = 'xls'; + /** + * Encoding + * @var boolean + */ + public $encoding = false; + /** * Default format * @var [type] @@ -499,7 +505,10 @@ protected function _setReaderDefaults() { // Set CSV delimiter if($this->format == 'CSV') + { $this->reader->setDelimiter(Config::get('excel::import.delimiter', ',')); + $this->reader->setInputEncoding(Config::get('excel::import.encoding', 'UTF-8')); + } // Set default calculate $this->calculate = Config::get('excel::import.calculate', true); diff --git a/src/config/import.php b/src/config/import.php index d2f8d65ea..6de71dbe8 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -29,6 +29,7 @@ | Input encoding |-------------------------------------------------------------------------- */ + 'encoding' => 'UTF-8', /* From e212c5e1154d9a50987b0371ea5525477bb15bc7 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 22:24:39 +0000 Subject: [PATCH 0030/1332] HTML Reader unicode support, fixes issue #69 --- src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php | 8 ++++++++ src/Maatwebsite/Excel/Readers/HtmlReader.php | 2 +- src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php | 8 ++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 59379c6d3..d98307e31 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -120,6 +120,14 @@ public function setDefaultPageSetup() } } + /** + * Set the view + */ + public function setView() + { + return call_user_func_array(array($this, 'loadView'), func_get_args()); + } + /** * * Load a View and convert to HTML diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index a5a4dbbba..eb14f130d 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -249,7 +249,7 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, foreach($element->childNodes as $child){ if ($child instanceof \DOMText) { - $domText = preg_replace('/\s+/',' ',trim($child->nodeValue)); + $domText = preg_replace('/\s+/u',' ',trim($child->nodeValue)); if (is_string($cellContent)) { // simply append the text if the cell content is a plain text string $cellContent .= $domText; diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 98ed6cf0e..0e50f5a7e 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -135,6 +135,14 @@ public function shareView($view, $data = array(), $mergeData = array()) return $this; } + /** + * Set the view + */ + public function setView() + { + return call_user_func_array(array($this, 'shareView'), func_get_args()); + } + /** * Load the view * @return [type] [description] From 250470387581c553b2be3201b2ab18d1b06e4f09 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 22:35:19 +0000 Subject: [PATCH 0031/1332] Autosize all sheet columns, all columns per sheet, or specific columns (setAutoSize(array('A'))) --- .../Excel/Classes/LaravelExcelWorksheet.php | 14 ++++++++++++ src/Maatwebsite/Excel/Readers/HtmlReader.php | 22 ++++++++++++++----- .../Excel/Writers/LaravelExcelWriter.php | 6 ++--- src/config/config.php | 8 ------- src/config/export.php | 7 ++++++ 5 files changed, 40 insertions(+), 17 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index d98307e31..c406a0533 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -374,6 +374,9 @@ public function getParent() */ public function setAutoSize($columns = false) { + // Set autosize to true + $this->autoSize = $columns ? $columns : false; + if(!is_array($columns) && $columns) { $toCol = $this->getHighestColumn(); @@ -392,7 +395,18 @@ public function setAutoSize($columns = false) } $this->calculateColumnWidths(); + } + + /** + * Get Auto size + * @return bool + */ + public function getAutosize() + { + if(isset($this->autoSize)) + return $this->autoSize; + return Config::get('excel::export.autosize', true); } /** diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index eb14f130d..6810a3e4b 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -233,14 +233,24 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, */ public function autosizeColumn($sheet) { - $toCol = $sheet->getHighestColumn(); + if($columns = $sheet->getAutosize()) + { + if(is_array($columns)) + { + $sheet->setAutoSize($columns); + } + else + { + $toCol = $sheet->getHighestColumn(); - $toCol++; - for ($i = 'A'; $i !== $toCol; $i++) { - $sheet->getColumnDimension($i)->setAutoSize(true); - } + $toCol++; + for ($i = 'A'; $i !== $toCol; $i++) { + $sheet->getColumnDimension($i)->setAutoSize(true); + } - $sheet->calculateColumnWidths(); + $sheet->calculateColumnWidths(); + } + } return $sheet; } diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 0e50f5a7e..d221f8257 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -147,9 +147,9 @@ public function setView() * Load the view * @return [type] [description] */ - public function loadView($view, $data = array(), $mergeData = array()) + public function loadView() { - return $this->shareView($view, $data, $mergeData); + return call_user_func_array(array($this, 'shareView'), func_get_args()); } /** @@ -174,7 +174,7 @@ public function sheet($title, $callback = false) $this->sheet->setDefaultPageSetup(); // Autosize columns - $this->sheet->setAutosize(Config::get('excel::sheets.autosize', false)); + $this->sheet->setAutosize(Config::get('excel::export.autosize', false)); // Do the callback if($callback instanceof \Closure) diff --git a/src/config/config.php b/src/config/config.php index 14267f4c8..d0acf6c70 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -62,14 +62,6 @@ 'printArea' => null, 'firstPageNumber' => null, ), - - /* - |-------------------------------------------------------------------------- - | Autosize columns - |-------------------------------------------------------------------------- - */ - 'autosize' => true - ), /* diff --git a/src/config/export.php b/src/config/export.php index b487809e0..57bf42d81 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -2,6 +2,13 @@ return array( + /* + |-------------------------------------------------------------------------- + | Autosize columns + |-------------------------------------------------------------------------- + */ + 'autosize' => false, + /* |-------------------------------------------------------------------------- | Store settings From 465f071cdce5a7951cbbec7e5207b9f8fa41ec01 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 22:45:20 +0000 Subject: [PATCH 0032/1332] Set the column width, fixes issue #72 --- .../Excel/Classes/LaravelExcelWorksheet.php | 25 +++++++++++++++++++ src/config/export.php | 4 +++ 2 files changed, 29 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index c406a0533..b210f81d1 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -367,6 +367,31 @@ public function getParent() return $this->_parent; } + /** + * Set the column width + * @param [type] $column [description] + * @param boolean $value [description] + */ + public function setWidth($column, $value = false) + { + // if is array of columns + if(is_array($column)) + { + // Set width for each column + foreach($column as $subColumn => $subValue) + { + return $this->setWidth($subColumn, $subValue); + } + } + else + { + // Set column width + $this->getColumnDimension($column)->setWidth($value); + } + + return $this; + } + /** * Autosize column for document * diff --git a/src/config/export.php b/src/config/export.php index 57bf42d81..43fdff75b 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -6,6 +6,10 @@ |-------------------------------------------------------------------------- | Autosize columns |-------------------------------------------------------------------------- + | + | Disable/enable column autosize or set the autosizing for + | an array of columns ( array('A', 'B') ) + | */ 'autosize' => false, From f81d6c971b045d91af1b07b0f54bfd3a7ec938ea Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 22:49:52 +0000 Subject: [PATCH 0033/1332] Set row height --- .../Excel/Classes/LaravelExcelWorksheet.php | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index b210f81d1..296c6953f 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -392,6 +392,31 @@ public function setWidth($column, $value = false) return $this; } + /** + * Set the row height + * @param [type] $row [description] + * @param boolean $value [description] + */ + public function setHeight($row, $value = false) + { + // if is array of columns + if(is_array($row)) + { + // Set width for each column + foreach($row as $subRow => $subValue) + { + return $this->setHeight($subRow, $subValue); + } + } + else + { + // Set column width + $this->getRowDimension($row)->setRowHeight($value); + } + + return $this; + } + /** * Autosize column for document * From 8d080a123189b3a05f178f4c1cafc9da60ed1569 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 22:57:02 +0000 Subject: [PATCH 0034/1332] Set cell sizes --- .../Excel/Classes/LaravelExcelWorksheet.php | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 296c6953f..9f2d7c1ec 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -417,6 +417,38 @@ public function setHeight($row, $value = false) return $this; } + /** + * [setSize description] + * @param [type] $cell [description] + * @param boolean $value [description] + */ + public function setSize($cell, $width = false, $height = false) + { + // if is array of columns + if(is_array($cell)) + { + // Set width for each column + foreach($cell as $subCell => $sizes) + { + return $this->setSize($subCell, reset($sizes), end($sizes)); + } + } + else + { + // Split the cell to column and row + list($column, $row) = preg_split('/(?<=[a-z])(?=[0-9]+)/i',$cell); + + if($column) + $this->setWidth($column, $width); + + if($row) + $this->setHeight($row, $height); + + } + + return $this; + } + /** * Autosize column for document * From 94a99b2249a6fad71825c73dee28a55fecfe4e8f Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 23:13:33 +0000 Subject: [PATCH 0035/1332] Colspan/rowspan bugfix, fixes issue #60 --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 43 +++++++++++++++++++- src/config/export.php | 2 +- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 6810a3e4b..5f0101b96 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -136,6 +136,18 @@ class Html extends \PHPExcel_Reader_HTML ), // Bottom border ); + /** + * The current colspan + * @var integer + */ + protected $spanWidth = 1; + + /** + * The current rowspan + * @var integer + */ + protected $spanHeight = 1; + /** * Loads PHPExcel from file * @@ -258,6 +270,10 @@ public function autosizeColumn($sheet) private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, &$cellContent){ foreach($element->childNodes as $child){ + + // set the spannend column size + //$this->spanWidth = 1; + if ($child instanceof \DOMText) { $domText = preg_replace('/\s+/u',' ',trim($child->nodeValue)); if (is_string($cellContent)) { @@ -481,7 +497,16 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, // echo 'END OF TABLE ' , $this->_tableLevel , ' ROW
'; // // Count the rows after the element was parsed - ++$row; + + // If we have a rowspan, count the right amount of rows, else just 1 + for($i = 0; $i < $this->spanHeight; $i++) + { + ++$row; + } + + // reset the span height after the process + $this->spanHeight = 1; + break; case 'th' : $this->_processHeadings($child, $sheet, $row, $column, $cellContent); @@ -492,7 +517,16 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, $this->_processDomElement($child,$sheet,$row,$column,$cellContent); // echo 'END OF TABLE ' , $this->_tableLevel , ' CELL
'; $this->_flushCell($sheet,$column,$row,$cellContent); - ++$column; + + // If we have a colspan, count the right amount of columns, else just 1 + for($i = 0; $i < $this->spanWidth; $i++) + { + ++$column; + } + + // reset the span width after the process + $this->spanWidth = 1; + break; case 'body' : $row = 1; @@ -633,6 +667,8 @@ protected function parseColSpan($sheet, $column, $row, $spanWidth) { $startCell = $column.$row; + $this->spanWidth = $spanWidth; + // Find end column letter for($i = 0; $i < ($spanWidth - 1); $i++) { @@ -659,6 +695,9 @@ protected function parseColSpan($sheet, $column, $row, $spanWidth) */ protected function parseRowSpan($sheet, $column, $row, $spanHeight) { + // Set the spanHeight + $this->spanHeight = $spanHeight; + $startCell = $column.$row; $endCell = $column.($row * $spanHeight); $range = $startCell . ':' . $endCell; diff --git a/src/config/export.php b/src/config/export.php index 43fdff75b..f968e34fb 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -11,7 +11,7 @@ | an array of columns ( array('A', 'B') ) | */ - 'autosize' => false, + 'autosize' => true, /* |-------------------------------------------------------------------------- From 1f92fb8e71a7e23c6b070491c38976c08733c2cc Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 23:15:46 +0000 Subject: [PATCH 0036/1332] Colspan fix on th aswell --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 5f0101b96..0e346c86d 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -510,7 +510,16 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, break; case 'th' : $this->_processHeadings($child, $sheet, $row, $column, $cellContent); - ++$column; + + // If we have a colspan, count the right amount of columns, else just 1 + for($i = 0; $i < $this->spanWidth; $i++) + { + ++$column; + } + + // reset the span width after the process + $this->spanWidth = 1; + break; case 'td' : // echo 'START OF TABLE ' , $this->_tableLevel , ' CELL
'; From 67df81be7589456f2d346d4e03cb761a9ffdc090 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 23:31:16 +0000 Subject: [PATCH 0037/1332] Remember() parsed results --- .../Excel/Readers/LaravelExcelReader.php | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 04a116206..c3f0761bc 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -111,6 +111,18 @@ class LaravelExcelReader { */ public $dateFormat; + /** + * Whether the results are cached or not + * @var boolean + */ + public $remembered = false; + + /** + * Amount of minutes the results will remain cached + * @var integer + */ + public $cacheMinutes = 10; + /** * Construct new writer * @param Response $response [description] @@ -140,6 +152,18 @@ public function load($file) return $this; } + /** + * Remember the results for x minutes + * @param [type] $minutes [description] + * @return [type] [description] + */ + public function remember($minutes) + { + $this->remembered = true; + $this->cacheMinutes = $minutes; + return $this; + } + /** * Read the file through a config file * @param [type] $config [description] @@ -188,8 +212,20 @@ public function all() */ public function get($columns = array()) { - $this->_parseFile($columns); - return $this->parsed; + if($this->remembered) + { + // Return cached results + return \Cache::remember(md5($this->file), $this->cacheMinutes, function() use (&$columns) { + $this->_parseFile($columns); + return $this->parsed; + }); + } + else + { + // return parsed file + $this->_parseFile($columns); + return $this->parsed; + } } /** From fa5855f6e61d0a80d9f32bb5fc7f3f4623022a4c Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 9 May 2014 23:37:50 +0000 Subject: [PATCH 0038/1332] Added XXE protection to HTML reader --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 0e346c86d..c626a7fa7 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -29,6 +29,7 @@ namespace Maatwebsite\Excel\Readers; use \PHPExcel; +use \PHPExcel_Settings; use \PHPExcel_Reader_HTML; use \PHPExcel_Style_Color; use \PHPExcel_Style_Border; @@ -211,12 +212,12 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, if($isHtmlFile) { // Load HTML from file - $loaded = @$dom->loadHTMLFile($pFilename); + $loaded = @$dom->loadHTMLFile($pFilename, PHPExcel_Settings::getLibXmlLoaderOptions()); } else { // Load HTML from string - $loaded = @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8')); + $loaded = @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8'), PHPExcel_Settings::getLibXmlLoaderOptions()); } if ($loaded === FALSE) { From 3ef1d0cddae92acefa2ff06de739016381ee72d6 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 00:03:21 +0000 Subject: [PATCH 0039/1332] Select 1 or multiple sheets to import --- src/Maatwebsite/Excel/Excel.php | 11 ++++++++ src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 -- .../Excel/Readers/LaravelExcelReader.php | 28 +++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 1fc2bdfee..67cc4325f 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -140,6 +140,17 @@ public function load($file, $callback = false) return $this->reader; } + /** + * Set select sheets + * @param [type] $sheets [description] + * @return [type] [description] + */ + public function selectSheets($sheets) + { + $this->reader->setSelectedSheets(is_array($sheets) ? $sheets : array($sheets)); + return $this; + } + /** * Batch import * @return [type] [description] diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 0dcae231e..67a4f29d5 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -131,9 +131,7 @@ public function parseFile($columns = array()) $workbook = $worksheet; break; } - $i++; - } } diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index c3f0761bc..46a2c2f15 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -123,6 +123,12 @@ class LaravelExcelReader { */ public $cacheMinutes = 10; + /** + * Selected sheets + * @var array + */ + public $selectedSheets = array(); + /** * Construct new writer * @param Response $response [description] @@ -145,6 +151,10 @@ public function load($file) // init the loading $this->_init($file); + // Only fetch selected sheets if necessary + if($this->sheetsSelected()) + $this->reader->setLoadSheetsOnly($this->selectedSheets); + // Load the file $this->excel = $this->reader->load($this->file); @@ -152,6 +162,24 @@ public function load($file) return $this; } + /** + * set selected sheets + * @param [type] $sheets [description] + */ + public function setSelectedSheets($sheets) + { + $this->selectedSheets = $sheets; + } + + /** + * Check if sheets were selected + * @return [type] [description] + */ + public function sheetsSelected() + { + return count($this->selectedSheets) > 0; + } + /** * Remember the results for x minutes * @param [type] $minutes [description] From 56b8ec32cf4bdf4513c6062c8f7e0b2f15f99114 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 17:44:31 +0000 Subject: [PATCH 0040/1332] Code cleanup --- docs/borders.md | 14 + docs/formats.md | 42 +++ docs/merge.md | 8 + .../Excel/Classes/LaravelExcelWorksheet.php | 228 +++---------- src/Maatwebsite/Excel/Classes/PHPExcel.php | 84 ++--- .../Excel/Collections/CellCollection.php | 11 + .../Excel/Collections/ExcelCollection.php | 11 + .../Excel/Collections/RowCollection.php | 11 + .../Excel/Collections/SheetCollection.php | 11 + src/Maatwebsite/Excel/Excel.php | 78 ++--- .../Excel/ExcelServiceProvider.php | 36 ++- .../Exceptions/LaravelExcelException.php | 11 + src/Maatwebsite/Excel/Facades/Excel.php | 19 +- src/Maatwebsite/Excel/Parsers/CssParser.php | 11 + src/Maatwebsite/Excel/Parsers/ExcelParser.php | 299 +++++++++++++----- src/Maatwebsite/Excel/Parsers/ViewParser.php | 14 +- src/Maatwebsite/Excel/Readers/Batch.php | 23 +- .../Excel/Readers/ConfigReader.php | 23 +- src/Maatwebsite/Excel/Readers/HtmlReader.php | 126 ++------ .../Excel/Readers/LaravelExcelReader.php | 21 +- .../Excel/Writers/LaravelExcelWriter.php | 46 +-- src/config/import.php | 15 +- 22 files changed, 593 insertions(+), 549 deletions(-) create mode 100644 docs/borders.md create mode 100644 docs/formats.md create mode 100644 docs/merge.md diff --git a/docs/borders.md b/docs/borders.md new file mode 100644 index 000000000..6207ac117 --- /dev/null +++ b/docs/borders.md @@ -0,0 +1,14 @@ +PHPExcel_Style_Border::BORDER_NONE = 'none' +PHPExcel_Style_Border::BORDER_DASHDOT = 'dashDot' +PHPExcel_Style_Border::BORDER_DASHDOTDOT = 'dashDotDot' +PHPExcel_Style_Border::BORDER_DASHED = 'dashed' +PHPExcel_Style_Border::BORDER_DOTTED = 'dotted' +PHPExcel_Style_Border::BORDER_DOUBLE = 'double' +PHPExcel_Style_Border::BORDER_HAIR = 'hair' +PHPExcel_Style_Border::BORDER_MEDIUM = 'medium' +PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT = 'mediumDashDot' +PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot' +PHPExcel_Style_Border::BORDER_MEDIUMDASHED = 'mediumDashed' +PHPExcel_Style_Border::BORDER_SLANTDASHDOT = 'slantDashDot' +PHPExcel_Style_Border::BORDER_THICK = 'thick' +PHPExcel_Style_Border::BORDER_THIN = 'thin' \ No newline at end of file diff --git a/docs/formats.md b/docs/formats.md new file mode 100644 index 000000000..b72cd0e22 --- /dev/null +++ b/docs/formats.md @@ -0,0 +1,42 @@ +PHPExcel_Style_NumberFormat::FORMAT_GENERAL = 'General' +PHPExcel_Style_NumberFormat::FORMAT_TEXT = '@' +PHPExcel_Style_NumberFormat::FORMAT_NUMBER = '0' +PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00 = '0.00' +PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00' +PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-' +PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE = '0%' +PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00 = '0.00%' +PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd' +PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD = 'yy-mm-dd' +PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY = 'dd/mm/yy' +PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH = 'd/m/y' +PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS = 'd-m-y' +PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS = 'd-m' +PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS = 'm-y' +PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14 = 'mm-dd-yy' +PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15 = 'd-mmm-yy' +PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16 = 'd-mmm' +PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17 = 'mmm-yy' +PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22 = 'm/d/yy h:mm' +PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME = 'd/m/y h:mm' +PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1 = 'h:mm AM/PM' +PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM' +PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3 = 'h:mm' +PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4 = 'h:mm:ss' +PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5 = 'mm:ss' +PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6 = 'h:mm:ss' +PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7 = 'i:s.S' +PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8 = 'h:mm:ss;@' +PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@' +PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-' +PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD = '$#,##0_-' +PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-' + +->setColumnFormat(array( + 'B' => '0', + 'D' => '0.00', + 'F' => '@', + 'F' => 'yyyy-mm-dd', + ...... + ) + ) \ No newline at end of file diff --git a/docs/merge.md b/docs/merge.md new file mode 100644 index 000000000..16be42cc3 --- /dev/null +++ b/docs/merge.md @@ -0,0 +1,8 @@ +$mergeColumn = array( + * 'columns' => array('A','B','C','D'), + * 'rows' => array( + * array(2,3), + * array(5,11), + * ..... + * ) + * ); \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 9f2d7c1ec..bb161240e 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -1,46 +1,23 @@ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL - * @version ##VERSION##, ##DATE## - */ - - -/** - * PHPExcel_Worksheet - * - * @category PHPExcel - * @package PHPExcel_Worksheet - * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) */ class LaravelExcelWorksheet extends PHPExcel_Worksheet { - /** * Parent * @var [type] @@ -76,7 +53,18 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet * @var array */ public $allowedPageSetup = array( - 'orientation', 'paperSize', 'scale', 'fitToPage', 'fitToHeight', 'fitToWidth', 'columnsToRepeatAtLeft', 'rowsToRepeatAtTop', 'horizontalCentered', 'verticalCentered', 'printArea', 'firstPageNumber' + 'orientation', + 'paperSize', + 'scale', + 'fitToPage', + 'fitToHeight', + 'fitToWidth', + 'columnsToRepeatAtLeft', + 'rowsToRepeatAtTop', + 'horizontalCentered', + 'verticalCentered', + 'printArea', + 'firstPageNumber' ); /** @@ -84,7 +72,9 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet * @var array */ public $allowedStyles = array( - 'fontFamily', 'fontSize', 'fontBold' + 'fontFamily', + 'fontSize', + 'fontBold' ); /** @@ -104,6 +94,7 @@ public function __construct(PHPExcel $pParent = null, $pTitle = 'Worksheet') */ public function setDefaultPageSetup() { + // Get the page setup $pageSetup = $this->getPageSetup(); foreach($this->allowedPageSetup as $setup) @@ -112,16 +103,17 @@ public function setDefaultPageSetup() list($setter, $set) = $this->_setSetter($setup); // get the value - $value = \Config::get('excel::sheets.pageSetup.' . $setup, NULL); + $value = Config::get('excel::sheets.pageSetup.' . $setup, NULL); // Set the page setup value if(!is_null($value)) - $pageSetup->{$setter}($value); + call_user_func_array(array($pageSetup, $setter), array($value)); } } /** * Set the view + * @return self */ public function setView() { @@ -135,7 +127,7 @@ public function setView() * @param string $view * @param array $data * @param array $mergeData - * @return static + * @return self * */ public function loadView($view, $data = array(), $mergeData = array()) @@ -163,6 +155,7 @@ public function unsetView() /** * Set the parser + * @param boolean $parser [description] */ public function setParser($parser = false) { @@ -285,6 +278,7 @@ protected function setDefaultStyles($setter, $key, $params) public function setStyle($styles) { $this->getDefaultStyle()->applyFromArray($styles); + return $This; } /** @@ -298,6 +292,7 @@ public function setFont($fonts) { $this->setFontStyle($this->getDefaultStyle(), $key, $key, $value); } + return $this; } /** @@ -459,15 +454,20 @@ public function setAutoSize($columns = false) // Set autosize to true $this->autoSize = $columns ? $columns : false; + // If is not an array if(!is_array($columns) && $columns) { + // Get the highest column $toCol = $this->getHighestColumn(); + // Lop through the columns and set the auto size $toCol++; for ($i = 'A'; $i !== $toCol; $i++) { $this->getColumnDimension($i)->setAutoSize(true); } } + + // Set autosize for the given columns elseif(is_array($columns)) { foreach($columns as $column) @@ -476,6 +476,7 @@ public function setAutoSize($columns = false) } } + // Calculate the column widths $this->calculateColumnWidths(); } @@ -503,17 +504,9 @@ public function setAutoFilter($value = false) } /** - * * Freeze or lock rows and columns - * - * @param string $pane rows and columns , default freeze the first row + * @param string $pane rows and columns * @return $this - * - * @author xiehai - * @example ->setFreeze() Freeze the first row - * ->setFreeze('B1') Freeze the first column (THE A COLUMN) - * ->setFreeze('B2') Freeze the first row and first column - * */ public function setFreeze($pane = 'A2') { @@ -552,36 +545,13 @@ public function freezeFirstRowAndColumn() } /** - * * Set a range of cell borders - * * @param string $pane Start and end of the cell (A1:F10) - * @param string $weight Border style (Reference setBorder style list) + * @param string $weight Border style * @return $this - * @example ->setBorder('A1:F10','thick') - * */ public function setBorder($pane = 'A1', $weight = 'thin') { - /* - @ ~ Border styles list ~ @ - - PHPExcel_Style_Border::BORDER_NONE = 'none' - PHPExcel_Style_Border::BORDER_DASHDOT = 'dashDot' - PHPExcel_Style_Border::BORDER_DASHDOTDOT = 'dashDotDot' - PHPExcel_Style_Border::BORDER_DASHED = 'dashed' - PHPExcel_Style_Border::BORDER_DOTTED = 'dotted' - PHPExcel_Style_Border::BORDER_DOUBLE = 'double' - PHPExcel_Style_Border::BORDER_HAIR = 'hair' - PHPExcel_Style_Border::BORDER_MEDIUM = 'medium' - PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT = 'mediumDashDot' - PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot' - PHPExcel_Style_Border::BORDER_MEDIUMDASHED = 'mediumDashed' - PHPExcel_Style_Border::BORDER_SLANTDASHDOT = 'slantDashDot' - PHPExcel_Style_Border::BORDER_THICK = 'thick' - PHPExcel_Style_Border::BORDER_THIN = 'thin' - */ - // Set all borders $this->getStyle($pane) ->getBorders() @@ -592,13 +562,9 @@ public function setBorder($pane = 'A1', $weight = 'thin') } /** - * * Set all cell borders - * * @param string $weight Border style (Reference setBorder style list) * @return $this - * @example Excel::create()->setAllBorder() Must follow the function of create() - * */ public function setAllBorders($weight = 'thin') { @@ -618,62 +584,10 @@ public function setAllBorders($weight = 'thin') } /** - * * Set the cell format of the column - * - * @return $this * @param array $formats An array of cells you want to format columns - * - * @author xiehai - * @example ->setColumnFormat(array( - * 'B' => '0', - * 'D' => '0.00', - * 'F' => '@', - * 'F' => 'yyyy-mm-dd', - * ...... - * ) - * ) - * @uses This method can only be used before the with() method - * + * @return $this */ - - /* - * @ ~ The Format list ~ @ - * - PHPExcel_Style_NumberFormat::FORMAT_GENERAL = 'General' - PHPExcel_Style_NumberFormat::FORMAT_TEXT = '@' - PHPExcel_Style_NumberFormat::FORMAT_NUMBER = '0' - PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00 = '0.00' - PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00' - PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-' - PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE = '0%' - PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00 = '0.00%' - PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd' - PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD = 'yy-mm-dd' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY = 'dd/mm/yy' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH = 'd/m/y' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS = 'd-m-y' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS = 'd-m' - PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS = 'm-y' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14 = 'mm-dd-yy' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15 = 'd-mmm-yy' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16 = 'd-mmm' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17 = 'mmm-yy' - PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22 = 'm/d/yy h:mm' - PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME = 'd/m/y h:mm' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1 = 'h:mm AM/PM' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3 = 'h:mm' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4 = 'h:mm:ss' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5 = 'mm:ss' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6 = 'h:mm:ss' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7 = 'i:s.S' - PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8 = 'h:mm:ss;@' - PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@' - PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-' - PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD = '$#,##0_-' - PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-' - */ public function setColumnFormat(Array $formats){ // Loop through the columns @@ -689,49 +603,9 @@ public function setColumnFormat(Array $formats){ } /** - * - * Set the cell width of the columns - * - * @return $this - * @param array $pane An array of column widths - * - * @author xiehai - * @example ->setColumnWidth(array( - * 'A' => '10', - * 'B' => '22', - * 'F' => '8', - * 'N' => '13', - * ...... - * ) - * ) - * - */ - public function setColumnWidth(Array $pane) - { - foreach ($pane as $column => $width) { - $this->getColumnDimension($column)->setWidth($width); - } - - return $this; - } - - /** - * * Set the columns you want to merge - * * @return $this * @param array $mergeColumn An array of columns you want to merge - * - * @author xiehai - * @example $mergeColumn = array( - * 'columns' => array('A','B','C','D'), - * 'rows' => array( - * array(2,3), - * array(5,11), - * ..... - * ) - * ); - * */ public function setMergeColumn(Array $mergeColumn) { @@ -744,21 +618,6 @@ public function setMergeColumn(Array $mergeColumn) return $this; } - /** - * Get style for cell - * - * @param string $pCellCoordinate Cell coordinate to get style for - * @return PHPExcel_Style - * @throws PHPExcel_Exception - */ - // public function getStyle($pCellCoordinate = 'A1') - // { - // // set cell coordinate as active - // $this->setSelectedCells($pCellCoordinate); - - // return $this->_parent->getCellXfSupervisor(); - // } - /** * Dynamically call methods * @param [type] $method [description] @@ -767,7 +626,6 @@ public function setMergeColumn(Array $mergeColumn) */ public function __call($method, $params) { - // If the dynamic call starts with "with", add the var to the data array if(starts_with($method, 'with')) { @@ -776,7 +634,7 @@ public function __call($method, $params) return $this; } - // If it's a stter + // If it's a setter elseif(starts_with($method, 'set') ) { // set the attribute @@ -786,6 +644,4 @@ public function __call($method, $params) throw new LaravelExcelException('[ERROR] Laravel Worksheet method ['. $method .'] does not exist.'); } - - -} +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index e2bb6f850..33ba12e18 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -1,78 +1,35 @@ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL - * @version ##VERSION##, ##DATE## - */ - - -/** - * PHPExcel - * - * @category PHPExcel - * @package PHPExcel - * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel extends PHPOffice_PHPExcel { - - /** - * Active sheet index - * - * @var int - */ - private $_activeSheetIndex = 0; - - /** - * View file - * @var [type] - */ - public $view; - - /** - * Data - * @var [type] - */ - public $data; - - /** - * Merge data - * @var [type] - */ - public $mergeData; - - public $_workSheetCollection = array(); - /** * Allowed autofill properties * @var array */ public $allowedProperties = array( - 'creator', 'lastModifiedBy', 'title', 'description', 'subject', 'keywords', 'category', 'manager', 'company' + 'creator', + 'lastModifiedBy', + 'title', + 'description', + 'subject', + 'keywords', + 'category', + 'manager', + 'company' ); /** @@ -84,16 +41,23 @@ class PHPExcel extends PHPOffice_PHPExcel */ public function createSheet($iSheetIndex = NULL, $title = false) { + // Init new Laravel Excel worksheet $newSheet = new LaravelExcelWorksheet($this, $title); + + // Add the sheet $this->addSheet($newSheet, $iSheetIndex); + + // Return the sheet return $newSheet; } /** * Set default properties + * @param [type] $custom [description] */ public function setDefaultProperties($custom) { + // Get the properties $properties = $this->getProperties(); // Get fillable properties @@ -106,7 +70,7 @@ public function setDefaultProperties($custom) $value = in_array($prop, array_keys($custom)) ? $custom[$prop] : \Config::get('excel::properties.' . $prop, NULL); // set the property - $properties->{$method}($value); + call_user_func_array(array($properties, $method), array($value)); } } diff --git a/src/Maatwebsite/Excel/Collections/CellCollection.php b/src/Maatwebsite/Excel/Collections/CellCollection.php index f8aee5fdd..e1d61eaf2 100644 --- a/src/Maatwebsite/Excel/Collections/CellCollection.php +++ b/src/Maatwebsite/Excel/Collections/CellCollection.php @@ -1,5 +1,16 @@ + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class CellCollection { /** diff --git a/src/Maatwebsite/Excel/Collections/ExcelCollection.php b/src/Maatwebsite/Excel/Collections/ExcelCollection.php index 26dc4c260..f679c28d6 100644 --- a/src/Maatwebsite/Excel/Collections/ExcelCollection.php +++ b/src/Maatwebsite/Excel/Collections/ExcelCollection.php @@ -2,4 +2,15 @@ use Illuminate\Support\Collection; +/** + * + * LaravelExcel ExcelCollection + * + * @category Laravel Excel + * @version 1.0.0 + * @package maatwebsite/excel + * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) + * @author Maatwebsite + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class ExcelCollection extends Collection {} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Collections/RowCollection.php b/src/Maatwebsite/Excel/Collections/RowCollection.php index 96bbb6348..06af4aab4 100644 --- a/src/Maatwebsite/Excel/Collections/RowCollection.php +++ b/src/Maatwebsite/Excel/Collections/RowCollection.php @@ -1,3 +1,14 @@ + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class RowCollection extends ExcelCollection {} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Collections/SheetCollection.php b/src/Maatwebsite/Excel/Collections/SheetCollection.php index 97de38bde..55e7bb7b0 100644 --- a/src/Maatwebsite/Excel/Collections/SheetCollection.php +++ b/src/Maatwebsite/Excel/Collections/SheetCollection.php @@ -1,3 +1,14 @@ + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class SheetCollection extends ExcelCollection {} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 67cc4325f..75b1edcc2 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -2,68 +2,41 @@ use \Closure; use \PHPExcel; -use Carbon\Carbon; -use \PHPExcel_Cell; -use \PHPExcel_IOFactory; -use \PHPExcel_Shared_Date; -use Illuminate\Support\Str; -use \PHPExcel_Style_NumberFormat; -use \PHPExcel_Worksheet_PageSetup; use Maatwebsite\Excel\Readers\Batch; -use Illuminate\View\Environment as View; -use Maatwebsite\Excel\Readers\HTML_reader; -use Illuminate\Config\Repository as Config; -use Illuminate\Filesystem\Filesystem as File; use Maatwebsite\Excel\Readers\LaravelExcelReader; use Maatwebsite\Excel\Writers\LaravelExcelWriter; -use Maatwebsite\Excel\Parsers\ViewParser; use Maatwebsite\Excel\Exceptions\LaravelExcelException; /** - * Laravel wrapper for PHPEXcel * - * @version 0.4.0 - * @package maatwebsite/excel - * @author Maatwebsite + * Laravel wrapper for PHPExcel + * + * @category Laravel Excel + * @version 1.0.0 + * @package maatwebsite/excel + * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) + * @author Maatwebsite + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ - class Excel { /** * Excel object * @var [type] */ - public $excel; - - /** - * Batch object - * @var [type] - */ - public $batch; - - /** - * Html reader - * @var [type] - */ - protected $htmlReader; + protected $excel; /** - * Config repository + * Reader object * @var [type] */ - protected $config; + protected $reader; /** - * View factory + * Writer object * @var [type] */ - protected $viewFactory; - - /** - * File system - * @var [type] - */ - protected $fileSystem; + protected $writer; /** * Construct Excel @@ -73,18 +46,12 @@ class Excel * @param View $view [description] * @param File $file [description] */ - public function __construct(PHPExcel $excel, LaravelExcelReader $reader, LaravelExcelWriter $writer, ViewParser $parser, Config $config, View $view, File $file) + public function __construct(PHPExcel $excel, LaravelExcelReader $reader, LaravelExcelWriter $writer) { // Set Excel dependencies $this->excel = $excel; $this->reader = $reader; $this->writer = $writer; - $this->parser = $parser; - - // Set Laravel classes - $this->config = $config; - $this->viewFactory = $view; - $this->fileSystem = $file; } /** @@ -99,6 +66,7 @@ public function create($title, $callback = false) 'title' => $title )); + // Disconnect worksheets to prevent unnecessary onces $this->excel->disconnectWorksheets(); // Inject our excel object @@ -120,7 +88,7 @@ public function create($title, $callback = false) * Load an existing file * * @param str $file The file we want to load - * @param bool $firstRowAsIndex Do we want to interpret de first row as labels? + * @param closure A callback * @return $this * */ @@ -166,12 +134,11 @@ public function batch($files, Closure $callback) */ public function shareView($view, $data = array(), $mergeData = array()) { - return $this->create('New file')->shareView($view, $data, $mergeData); + return $this->create($view)->shareView($view, $data, $mergeData); } /** * Create a new file and load a view - * [NOT RECOMMENDED TO USE; ONLY FOR BACKWARDS COMPATABILITY] * @return [type] [description] */ public function loadView($view, $data = array(), $mergeData = array()) @@ -187,17 +154,8 @@ public function loadView($view, $data = array(), $mergeData = array()) */ public function __call($method, $params) { - // If the dynamic call starts with "with", add the var to the data array - if(starts_with($method, 'with')) - { - $key = lcfirst(str_replace('with', '', $method)); - $this->addVars($key, reset($params)); - return $this; - } - - // Call a php excel method - elseif(method_exists($this->excel, $method)) + if(method_exists($this->excel, $method)) { // Call the method from the excel object with the given params return call_user_func_array(array($this->excel, $method), $params); diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index d9d22ed68..f698e674c 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -8,6 +8,17 @@ use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; use Maatwebsite\Excel\Parsers\ViewParser; +/** + * + * LaravelExcel Excek ServiceProvider + * + * @category Laravel Excel + * @version 1.0.0 + * @package maatwebsite/excel + * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) + * @author Maatwebsite + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class ExcelServiceProvider extends ServiceProvider { /** @@ -38,7 +49,6 @@ public function register() $this->bindReaders(); $this->bindParsers(); $this->bindPHPExcelClass(); - $this->bindClasses(); $this->bindWriters(); $this->bindExcel(); } @@ -55,29 +65,21 @@ protected function bindPHPExcelClass() }); } - /** - * Bind Classes - * @return [type] [description] - */ - protected function bindClasses() - { - - } - /** * Bind writers * @return [type] [description] */ protected function bindReaders() { - // Bind the laravel excel reader - $this->app['excel.reader'] = $this->app->share(function($app) { + $this->app['excel.reader'] = $this->app->share(function($app) + { return new LaravelExcelReader($app['files']); }); // Bind the html reader class - $this->app['excel.readers.html'] = $this->app->share(function($app) { + $this->app['excel.readers.html'] = $this->app->share(function($app) + { return new Html(); }); } @@ -88,7 +90,9 @@ protected function bindReaders() */ protected function bindParsers() { - $this->app['excel.parsers.view'] = $this->app->share(function($app) { + // Bind the view parser + $this->app['excel.parsers.view'] = $this->app->share(function($app) + { return new ViewParser($app['excel.readers.html']); }); } @@ -99,7 +103,9 @@ protected function bindParsers() */ protected function bindWriters() { - $this->app['excel.writer'] = $this->app->share(function($app) { + // Bind the excel writer + $this->app['excel.writer'] = $this->app->share(function($app) + { return new LaravelExcelWriter($app->make('Response'), $app['files']); }); } diff --git a/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php b/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php index 8e700ddac..b97063a0c 100644 --- a/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php +++ b/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php @@ -2,4 +2,15 @@ use \PHPExcel_Exception; +/** + * + * LaravelExcel Exception + * + * @category Laravel Excel + * @version 1.0.0 + * @package maatwebsite/excel + * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) + * @author Maatwebsite + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class LaravelExcelException extends PHPExcel_Exception {} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Facades/Excel.php b/src/Maatwebsite/Excel/Facades/Excel.php index 406c4414e..9508782b5 100644 --- a/src/Maatwebsite/Excel/Facades/Excel.php +++ b/src/Maatwebsite/Excel/Facades/Excel.php @@ -1,11 +1,24 @@ - + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class Excel extends Facade { + /** + * Return facade accessor + * @return [type] [description] + */ protected static function getFacadeAccessor() { return 'excel'; diff --git a/src/Maatwebsite/Excel/Parsers/CssParser.php b/src/Maatwebsite/Excel/Parsers/CssParser.php index 7a22dd1cc..1bce65a83 100644 --- a/src/Maatwebsite/Excel/Parsers/CssParser.php +++ b/src/Maatwebsite/Excel/Parsers/CssParser.php @@ -2,6 +2,17 @@ use \URL; +/** + * + * LaravelExcel CSS Parser + * + * @category Laravel Excel + * @version 1.0.0 + * @package maatwebsite/excel + * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) + * @author Maatwebsite + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class CssParser { /** diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 67a4f29d5..8e8d64acd 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -3,19 +3,25 @@ use \Config; use Carbon\Carbon; use \PHPExcel_Cell; -use \PHPExcel_IOFactory; use \PHPExcel_Shared_Date; use Illuminate\Support\Str; use \PHPExcel_Style_NumberFormat; -use \PHPExcel_Worksheet_PageSetup; -use Illuminate\Filesystem\Filesystem; -use Maatwebsite\Excel\Parsers\ExcelParser; -use Maatwebsite\Excel\Exceptions\LaravelExcelException; -use Illuminate\Support\Collection; -use Maatwebsite\Excel\Collections\SheetCollection; use Maatwebsite\Excel\Collections\RowCollection; use Maatwebsite\Excel\Collections\CellCollection; +use Maatwebsite\Excel\Collections\SheetCollection; +use Maatwebsite\Excel\Exceptions\LaravelExcelException; +/** + * + * LaravelExcel Excel Parser + * + * @category Laravel Excel + * @version 1.0.0 + * @package maatwebsite/excel + * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) + * @author Maatwebsite + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class ExcelParser { /** @@ -93,34 +99,23 @@ public function parseFile($columns = array()) // Init new sheet collection $workbook = new SheetCollection(); - // Set the columns - $this->columns = $columns; + // Set the selected columns + $this->setSelectedColumns($columns); + // If not parsed yet if(!$this->isParsed) { // Set worksheet count - $i = 0; + $this->w = 0; // Loop through the worksheets foreach($this->excel->getWorksheetIterator() as $this->worksheet) { - // Set the active worksheet - $this->excel->setActiveSheetIndex($i); - - // Get the worksheet name - $title = $this->excel->getActiveSheet()->getTitle(); - - // Fetch the labels - $this->indices = $this->reader->hasHeading() ? $this->getIndices() : array(); - - // Parse the rows - $worksheet = $this->parseRows(); - - // Get the sheet count - $this->sheetCount = $this->excel->getSheetCount(); + // Parse the worksheet + $worksheet = $this->parseWorksheet(); // If multiple sheets - if($this->sheetCount > 1) + if($this->parseAsMultiple()) { // Push every sheet $workbook->push($worksheet); @@ -131,7 +126,7 @@ public function parseFile($columns = array()) $workbook = $worksheet; break; } - $i++; + $this->w++; } } @@ -141,6 +136,34 @@ public function parseFile($columns = array()) return $workbook; } + /** + * Check if we want to parse it as multiple sheets + * @return [type] [description] + */ + protected function parseAsMultiple() + { + return $this->excel->getSheetCount() > 1 || Config::get('excel::import.force_sheets_collection', false); + } + + /** + * Parse the worksheet + * @return [type] [description] + */ + protected function parseWorksheet() + { + // Set the active worksheet + $this->excel->setActiveSheetIndex($this->w); + + // Get the worksheet name + $title = $this->excel->getActiveSheet()->getTitle(); + + // Fetch the labels + $this->indices = $this->reader->hasHeading() ? $this->getIndices() : array(); + + // Parse the rows + return $this->parseRows(); + } + /** * * Get the labels @@ -186,11 +209,12 @@ protected function parseRows() foreach ($this->worksheet->getRowIterator() as $this->row) { // Limit the results - if($this->reader->limit && $this->r == ($this->reader->limit + 1) ) + if($this->checkForLimit()) break; // Ignore first row when needed if($this->r >= $ignore) + // Push the parsed cells inside the parsed rows $parsedRows->push($this->parseCells()); // Count the rows @@ -201,12 +225,19 @@ protected function parseRows() return $parsedRows; } - /** - * - * Parse the cells - * - * @return $this - * + /** + * Check for the limit + * @return [type] [description] + */ + protected function checkForLimit() + { + // If we have a limit, check if we hit this limit + return $this->reader->limit && $this->r == ($this->reader->limit + 1); + } + + /** + * Parse the cells of the given row + * @return [type] [description] */ protected function parseCells() { @@ -216,73 +247,177 @@ protected function parseCells() // Set the cell iterator $cellIterator = $this->row->getCellIterator(); - // Ignore empty cells + // Ignore empty cells if needed $cellIterator->setIterateOnlyExistingCells($this->reader->needsIgnoreEmpty()); // Foreach cells foreach ($cellIterator as $this->cell) { - // Get the cell index - $index = PHPExcel_Cell::columnIndexFromString($this->cell->getColumn()); - // Check how we need to save the parsed array - $index = $this->reader->hasHeading() ? $this->indices[$i] : $i; + $index = $this->reader->hasHeading() ? $this->indices[$i] : $this->getIndexFromColumn(); // Check if we want to select this column - if(empty($this->columns) || (!empty($this->columns) && in_array($index, $this->columns) ) ) + if($this->cellNeedsParsing($index) ) { - // If the cell is a date time - if(PHPExcel_Shared_Date::isDateTime($this->cell) || in_array($index, $this->reader->getDateColumns())) - { - if($this->reader->needsDateFormatting()) - { - // Convert excel time to php date object - $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format(false); - - // Parse with carbon - $date = Carbon::parse($date); - - // Format the date if wanted - $value = $this->reader->getDateFormat() ? $date->format($this->reader->getDateFormat()) : $date; - } - else - { - //Format the date to a formatted string - $value = (string) PHPExcel_Style_NumberFormat::toFormattedString( - $this->cell->getCalculatedValue(), - $this->cell->getWorksheet()->getParent() - ->getCellXfByIndex($this->cell->getXfIndex()) - ->getNumberFormat() - ->getFormatCode() - ); - } - - } - - // Check if we want calculated values or not - elseif($this->reader->needsCalculation()) - { - // Get calculated value - $value = $this->cell->getCalculatedValue(); - } - else - { - // Get real value - $value = $this->cell->getValue(); - $value = iconv(Config::get('excel::import.encoding', 'UTF-8'), 'CP1252', $value); - } - // Set the value - $parsedCells[$index] = $value; + $parsedCells[$index] = $this->parseCell($index); } $i++; - } // Return array with parsed cells return CellCollection::make($parsedCells); + } + + /** + * Parse a single cell + * @return [type] [description] + */ + protected function parseCell($index) + { + // If the cell is a date time + if($this->cellIsDate($index)) + { + // Parse the date + return $this->parseDate(); + } + + // Check if we want calculated values or not + elseif($this->reader->needsCalculation()) + { + // Get calculated value + return $this->cell->getCalculatedValue(); + } + else + { + // Get real value + return $this->getCellValue(); + } + } + + /** + * Return the cell value + * @return [type] [description] + */ + protected function getCellValue() + { + // get the value + $value = $this->cell->getValue(); + + // return encoded string + return iconv(Config::get('excel::import.encoding', 'UTF-8'), 'CP1252', $value); + } + + /** + * Parse the date + * @return [type] [description] + */ + protected function parseDate() + { + // If the date needs formatting + if($this->reader->needsDateFormatting()) + { + // Parse the date with carbon + return $this->parseDateAsCarbon(); + } + else + { + // Parse the date as a normal string + return $this->parseDateAsString(); + } + } + + /** + * Parse and return carbon object or formatted time string + * @return [type] [description] + */ + protected function parseDateAsCarbon() + { + // Convert excel time to php date object + $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format(false); + + // Parse with carbon + $date = Carbon::parse($date); + + // Format the date if wanted + return $this->reader->getDateFormat() ? $date->format($this->reader->getDateFormat()) : $date; + } + + /** + * Return date string + * @return [type] [description] + */ + protected function parseDateAsString() + { + //Format the date to a formatted string + return (string) PHPExcel_Style_NumberFormat::toFormattedString( + $this->cell->getCalculatedValue(), + $this->cell->getWorksheet()->getParent() + ->getCellXfByIndex($this->cell->getXfIndex()) + ->getNumberFormat() + ->getFormatCode() + ); + } + + /** + * Check if cell is a date + * @param [type] $index [description] + * @return [type] [description] + */ + protected function cellIsDate($index) + { + // if is a date or if is a date column + return PHPExcel_Shared_Date::isDateTime($this->cell) || in_array($index, $this->reader->getDateColumns()); + } + + /** + * Check if cells needs parsing + * @return [type] [description] + */ + protected function cellNeedsParsing($index) + { + // if no columns are selected or if the column is selected + return !$this->hasSelectedColumns() || ($this->hasSelectedColumns() && in_array($index, $this->getSelectedColumns())); + } + + /** + * Get the cell index from column + * @return [type] [description] + */ + protected function getIndexFromColumn() + { + return PHPExcel_Cell::columnIndexFromString($this->cell->getColumn()); + } + + /** + * Set selected columns + * @param array $columns [description] + */ + protected function setSelectedColumns($columns = array()) + { + // Set the columns + $this->columns = $columns; + } + + /** + * Check if we have selected columns + * @return boolean [description] + */ + protected function hasSelectedColumns() + { + return !empty($this->getSelectedColumns()); + } + + /** + * Set selected columns + * @param array $columns [description] + */ + protected function getSelectedColumns() + { + // Set the columns + return $this->columns; } diff --git a/src/Maatwebsite/Excel/Parsers/ViewParser.php b/src/Maatwebsite/Excel/Parsers/ViewParser.php index 5c0fd3c82..1b1e5de91 100644 --- a/src/Maatwebsite/Excel/Parsers/ViewParser.php +++ b/src/Maatwebsite/Excel/Parsers/ViewParser.php @@ -1,7 +1,19 @@ + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class ViewParser { /** @@ -38,7 +50,7 @@ public function __construct(Html $reader) */ public function parse($sheet) { - $html = \View::make($this->view, $this->data, $this->mergeData)->render(); + $html = View::make($this->view, $this->data, $this->mergeData)->render(); return $this->_loadHTML($sheet, $html); } diff --git a/src/Maatwebsite/Excel/Readers/Batch.php b/src/Maatwebsite/Excel/Readers/Batch.php index 181896132..c3a6aa8ab 100644 --- a/src/Maatwebsite/Excel/Readers/Batch.php +++ b/src/Maatwebsite/Excel/Readers/Batch.php @@ -4,6 +4,17 @@ use Maatwebsite\Excel\Excel; use Maatwebsite\Excel\Exceptions\LaravelExcelException; +/** + * + * LaravelExcel Batch Importer + * + * @category Laravel Excel + * @version 1.0.0 + * @package maatwebsite/excel + * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) + * @author Maatwebsite + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class Batch { /** @@ -23,7 +34,9 @@ class Batch { * @var array */ protected $allowedFileExtensions = array( - 'xls', 'xlsx', 'csv' + 'xls', + 'xlsx', + 'csv' ); /** @@ -43,11 +56,15 @@ public function __construct(Excel $excel, $files, Closure $callback) { foreach($this->getFiles() as $file) { + // Load the file $excel = $this->excel->load($file); + + // Do a callback with the loaded file call_user_func($callback, $excel, $file); } } + // Return our excel object return $this->excel; } @@ -64,7 +81,7 @@ public function getFiles() * Set the batch files * @param [type] $files [description] */ - public function _setFiles($files) + protected function _setFiles($files) { // If the param is an array, these will be the files for the batch import if(is_array($files)) @@ -111,8 +128,10 @@ protected function _getFilesByFolder($folder) // Find path names matching our pattern of excel extensions $glob = glob($folder.'/*.{'. implode(',', $this->allowedFileExtensions) .'}', GLOB_BRACE); + // If no matches, return empty array if ($glob === false) return array(); + // Return files return array_filter($glob, function($file) { return filetype($file) == 'file'; }); diff --git a/src/Maatwebsite/Excel/Readers/ConfigReader.php b/src/Maatwebsite/Excel/Readers/ConfigReader.php index 71c8fdb00..6b212d17b 100644 --- a/src/Maatwebsite/Excel/Readers/ConfigReader.php +++ b/src/Maatwebsite/Excel/Readers/ConfigReader.php @@ -1,11 +1,22 @@ + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class ConfigReader { /** @@ -100,10 +111,13 @@ public function getSheetCollection() */ protected function valueByIndex($field) { + // Convert field name $field = snake_case($field); + // Get coordinate if($coordinate = $this->getCoordinateByKey($field)) { + // return cell value by coordinate return $this->getCellValueByCoordinate($coordinate); } @@ -145,6 +159,11 @@ protected function getCoordinateByKey($field) return Config::get($this->configName . '.' . $this->sheetName . '.' . $field, false); } + /** + * Dynamically get a value by config + * @param [type] $field [description] + * @return [type] [description] + */ public function __get($field) { return $this->valueByIndex($field); diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index c626a7fa7..d09e8d98f 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -1,33 +1,6 @@ - + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ +class Html extends PHPExcel_Reader_HTML { /** @@ -60,82 +45,7 @@ class Html extends \PHPExcel_Reader_HTML * HTML tags formatting settings * @var array */ - private $_formats = array( - 'th' => array( - 'font' => array( - 'bold' => true, - 'size' => 12, - ), - ), - 'strong' => array( - 'font' => array( - 'bold' => true, - 'size' => 12, - ), - ), - 'b' => array( - 'font' => array( - 'bold' => true, - 'size' => 12, - ), - ), - 'i' => array( - 'font' => array( - 'italic' => true, - 'size' => 12, - ), - ), - 'h1' => array( - 'font' => array( - 'bold' => true, - 'size' => 24, - ), - ), // Bold, 24pt - 'h2' => array( - 'font' => array( - 'bold' => true, - 'size' => 18, - ), - ), // Bold, 18pt - 'h3' => array( - 'font' => array( - 'bold' => true, - 'size' => 13.5, - ), - ), // Bold, 13.5pt - 'h4' => array( - 'font' => array( - 'bold' => true, - 'size' => 12, - ), - ), // Bold, 12pt - 'h5' => array( - 'font' => array( - 'bold' => true, - 'size' => 10, - ), - ), // Bold, 10pt - 'h6' => array( - 'font' => array( - 'bold' => true, - 'size' => 7.5, - ), - ), // Bold, 7.5pt - 'a' => array( - 'font' => array( - 'underline' => true, - 'color' => array( 'argb' => PHPExcel_Style_Color::COLOR_BLUE), - ), - ), // Blue underlined - 'hr' => array( - 'borders' => array( - 'bottom' => array( - 'style' => PHPExcel_Style_Border::BORDER_THIN, - 'color' => array(PHPExcel_Style_Color::COLOR_BLACK) - ), - ), - ), // Bottom border - ); + private $_formats = array(); /** * The current colspan @@ -158,6 +68,8 @@ class Html extends \PHPExcel_Reader_HTML */ public function load($pFilename, $isString = false, $obj = false) { + // Set the default style formats + $this->setStyleFormats(); if($obj instanceof \PHPExcel) { @@ -174,6 +86,7 @@ public function load($pFilename, $isString = false, $obj = false) return $this->loadIntoExisting($pFilename, $objPHPExcel, $isString); } + /** * Loads HTML from file into sheet instance * @@ -184,7 +97,6 @@ public function load($pFilename, $isString = false, $obj = false) */ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, $isString = false) { - $isHtmlFile = FALSE; // Check if it's a string or file diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 46a2c2f15..8ec49e909 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -5,8 +5,18 @@ use Illuminate\Filesystem\Filesystem; use Maatwebsite\Excel\Parsers\ExcelParser; use Maatwebsite\Excel\Exceptions\LaravelExcelException; -use Illuminate\Support\Collection; +/** + * + * LaravelExcel Excel reader + * + * @category Laravel Excel + * @version 1.0.0 + * @package maatwebsite/excel + * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) + * @author Maatwebsite + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class LaravelExcelReader { /** @@ -234,6 +244,15 @@ public function all() return $this->get(); } + /** + * Get first row only + * @return [type] [description] + */ + public function first() + { + return $this->take(1)->get()->first(); + } + /** * Get all sheets/rows * @return [type] [description] diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index d221f8257..efd4fb21f 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -4,9 +4,20 @@ use \Response; use Carbon\Carbon; use Illuminate\Filesystem\Filesystem; -use Maatwebsite\Excel\Exceptions\LaravelExcelException; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; +use Maatwebsite\Excel\Exceptions\LaravelExcelException; +/** + * + * LaravelExcel Excel writer + * + * @category Laravel Excel + * @version 1.0.0 + * @package maatwebsite/excel + * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) + * @author Maatwebsite + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ class LaravelExcelWriter { /** @@ -63,30 +74,6 @@ class LaravelExcelWriter { */ protected $rendered = false; - /** - * Sheet count - * @var integer - */ - protected $sheetCount = -1; - - /** - * View - * @var [type] - */ - protected $view; - - /** - * Data - * @var [type] - */ - protected $data = array(); - - /** - * Merge data - * @var array - */ - protected $mergeData = array(); - /** * Construct new writer * @param Response $response [description] @@ -128,6 +115,7 @@ public function shareView($view, $data = array(), $mergeData = array()) if(!$this->parser) $this->parser = app('excel.parsers.view'); + // Set the view inside the parser $this->parser->setView($view); $this->parser->setData($data); $this->parser->setMergeData($mergeData); @@ -183,9 +171,6 @@ public function sheet($title, $callback = false) // Parse the sheet $this->sheet->parsed(); - // Count sheets - $this->sheetCount++; - return $this; } @@ -195,7 +180,7 @@ public function sheet($title, $callback = false) * @param boolean $value [description] * @return [type] [description] */ - public function with($array) + public function with(Array $array) { // Add the vars $this->fromArray($array); @@ -457,6 +442,9 @@ public function __call($method, $params) } + /** + * On destruct + */ public function __destruct() { $this->excel->disconnectWorksheets(); diff --git a/src/config/import.php b/src/config/import.php index 6de71dbe8..04db8d172 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -56,7 +56,7 @@ 'calculate' => true, - /* + /* |-------------------------------------------------------------------------- | Ignore empty cells |-------------------------------------------------------------------------- @@ -67,6 +67,19 @@ 'ignoreEmpty' => false, + /* + |-------------------------------------------------------------------------- + | Force sheet collection + |-------------------------------------------------------------------------- + | + | For a sheet collection even when there is only 1 sheets. + | When set to false and only 1 sheet found, the parsed file will return + | a row collection instead of a sheet collection. + | When set to true, it will return a sheet collection instead. + | + */ + 'force_sheets_collection' => false, + /* |-------------------------------------------------------------------------- | Date format From 52e9c092e2893d1731d79949bb045293173a3597 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 17:45:10 +0000 Subject: [PATCH 0041/1332] Move default style formats for views to config file --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 7 + src/config/views.php | 163 +++++++++++++++++++ 2 files changed, 170 insertions(+) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index d09e8d98f..110c8bdc0 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -86,6 +86,13 @@ public function load($pFilename, $isString = false, $obj = false) return $this->loadIntoExisting($pFilename, $objPHPExcel, $isString); } + /** + * Set the style formats from our config file + */ + protected function setStyleFormats() + { + $this->_formats = Config::get('excel::views.styles', array()); + } /** * Loads HTML from file into sheet instance diff --git a/src/config/views.php b/src/config/views.php index e69de29bb..523212955 100644 --- a/src/config/views.php +++ b/src/config/views.php @@ -0,0 +1,163 @@ + array( + + /* + |-------------------------------------------------------------------------- + | Table headings + |-------------------------------------------------------------------------- + */ + 'th' => array( + 'font' => array( + 'bold' => true, + 'size' => 12, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Strong tags + |-------------------------------------------------------------------------- + */ + 'strong' => array( + 'font' => array( + 'bold' => true, + 'size' => 12, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Bold tags + |-------------------------------------------------------------------------- + */ + 'b' => array( + 'font' => array( + 'bold' => true, + 'size' => 12, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Italic tags + |-------------------------------------------------------------------------- + */ + 'i' => array( + 'font' => array( + 'italic' => true, + 'size' => 12, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Heading 1 + |-------------------------------------------------------------------------- + */ + 'h1' => array( + 'font' => array( + 'bold' => true, + 'size' => 24, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Heading 2 + |-------------------------------------------------------------------------- + */ + 'h2' => array( + 'font' => array( + 'bold' => true, + 'size' => 18, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Heading 2 + |-------------------------------------------------------------------------- + */ + 'h3' => array( + 'font' => array( + 'bold' => true, + 'size' => 13.5, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Heading 4 + |-------------------------------------------------------------------------- + */ + 'h4' => array( + 'font' => array( + 'bold' => true, + 'size' => 12, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Heading 5 + |-------------------------------------------------------------------------- + */ + 'h5' => array( + 'font' => array( + 'bold' => true, + 'size' => 10, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Heading 6 + |-------------------------------------------------------------------------- + */ + 'h6' => array( + 'font' => array( + 'bold' => true, + 'size' => 7.5, + ) + ), + + /* + |-------------------------------------------------------------------------- + | Hyperlinks + |-------------------------------------------------------------------------- + */ + 'a' => array( + 'font' => array( + 'underline' => true, + 'color' => array( 'argb' => 'FF0000FF'), + ) + ), + + /* + |-------------------------------------------------------------------------- + | Horizontale rules + |-------------------------------------------------------------------------- + */ + 'hr' => array( + 'borders' => array( + 'bottom' => array( + 'style' => 'thin', + 'color' => array('FF000000') + ), + ) + ) + ) + +); \ No newline at end of file From 8a04aa83acb494d487f324573c343acc9a7c176d Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 18:10:21 +0000 Subject: [PATCH 0042/1332] HTML reader clean-up --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 329 ++++++++++++++----- 1 file changed, 238 insertions(+), 91 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 110c8bdc0..3769b8d31 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -2,6 +2,10 @@ use \Config; use \PHPExcel; +use \domDocument; +use \DOMNode; +use \DOMText; +use \DOMElement; use \PHPExcel_Settings; use \PHPExcel_Reader_HTML; use \PHPExcel_Style_Color; @@ -71,7 +75,7 @@ public function load($pFilename, $isString = false, $obj = false) // Set the default style formats $this->setStyleFormats(); - if($obj instanceof \PHPExcel) + if($obj instanceof PHPExcel) { // Load into this instance return $this->loadIntoExisting($pFilename, $obj, $isString); @@ -82,7 +86,7 @@ public function load($pFilename, $isString = false, $obj = false) return $this->loadIntoExistingSheet($pFilename, $obj, $isString); } - $objPHPExcel = $obj ? $obj : new \PHPExcel(); + $objPHPExcel = $obj ? $obj : new PHPExcel(); return $this->loadIntoExisting($pFilename, $objPHPExcel, $isString); } @@ -110,12 +114,14 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, if(!$isString) { // Double check if it's a file - if(is_file($pFilename)){ + if(is_file($pFilename)) + { + $isHtmlFile = TRUE; - // Open file to validate $this->_openFile($pFilename); - if (!$this->_isValidFormat()) { + if (!$this->_isValidFormat()) + { fclose ($this->_fileHandle); throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid HTML file."); } @@ -125,7 +131,7 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, } // Create a new DOM object - $dom = new \domDocument; + $dom = new domDocument; // Check if we need to load the file or the HTML if($isHtmlFile) @@ -139,8 +145,9 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, $loaded = @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8'), PHPExcel_Settings::getLibXmlLoaderOptions()); } - if ($loaded === FALSE) { - throw new \PHPExcel_Reader_Exception('Failed to load ',$pFilename,' as a DOM Document'); + if ($loaded === FALSE) + { + throw new PHPExcel_Reader_Exception('Failed to load ',$pFilename,' as a DOM Document'); } // Parse css @@ -174,7 +181,6 @@ public function autosizeColumn($sheet) else { $toCol = $sheet->getHighestColumn(); - $toCol++; for ($i = 'A'; $i !== $toCol; $i++) { $sheet->getColumnDimension($i)->setAutoSize(true); @@ -187,60 +193,78 @@ public function autosizeColumn($sheet) return $sheet; } - private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, &$cellContent){ + /** + * Proccess the dom element + * @param DOMNode $element [description] + * @param [type] $sheet [description] + * @param [type] $row [description] + * @param [type] $column [description] + * @param [type] $cellContent [description] + * @return [type] [description] + */ + private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, &$cellContent){ foreach($element->childNodes as $child){ - // set the spannend column size - //$this->spanWidth = 1; - - if ($child instanceof \DOMText) { + // If is text + if ($child instanceof DOMText) + { + // get the dom text $domText = preg_replace('/\s+/u',' ',trim($child->nodeValue)); + + // simply append the text if the cell content is a plain text string if (is_string($cellContent)) { - // simply append the text if the cell content is a plain text string $cellContent .= $domText; - } else { - // but if we have a rich text run instead, we need to append it correctly - // TODO } - } elseif($child instanceof \DOMElement) { - // echo 'DOM ELEMENT: ' , strtoupper($child->nodeName) , '
'; + } + + // If is a dom element + elseif($child instanceof DOMElement) + { $attributeArray = array(); - foreach($child->attributes as $attribute) { - // echo 'ATTRIBUTE: ' , $attribute->name , ' => ' , $attribute->value , '
'; + + // Loop through the child's attributes + foreach($child->attributes as $attribute) + { + // Add the attribute to the array $attributeArray[$attribute->name] = $attribute->value; // Attribute names - switch($attribute->name) { + switch($attribute->name) + { + // Inline css styles case 'style': - - // Pare style tags $this->parseInlineStyles($sheet, $column, $row, $attribute->value); - break; + // Colspan case 'colspan': $this->parseColSpan($sheet, $column, $row, $attribute->value); break; + // Rowspan case 'rowspan': $this->parseRowSpan($sheet, $column, $row, $attribute->value); break; + // Alignment case 'align': $this->parseAlign($sheet, $column, $row, $attribute->value); break; + // Vertical alignment case 'valign': $this->parseValign($sheet, $column, $row, $attribute->value); break; + // Classes case 'class': $this->styleByClass($sheet, $column, $row, $attribute->value); break; + // Ids case 'id': $this->styleById($sheet, $column, $row, $attribute->value); break; @@ -251,24 +275,37 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, } // nodeName - switch($child->nodeName) { + switch($child->nodeName) + { + // Meta tags case 'meta' : + + // Loop through the attributes foreach($attributeArray as $attributeName => $attributeValue) { + + // Switch the names switch($attributeName) { - case 'content': - // TODO - // Extract character set, so we can convert to UTF-8 if required + // Set input encoding + case 'charset': + $_inputEncoding = $attributeValue; break; } } + + // Continue processing dom element $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + break; + + // Set sheet title case 'title' : $this->_processDomElement($child,$sheet,$row,$column,$cellContent); $sheet->setTitle($cellContent); $cellContent = ''; break; + + // Text case 'span' : case 'div' : case 'font' : @@ -277,59 +314,98 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, case 'strong': case 'b' : -// echo 'STYLING, SPAN OR DIV
'; + // Add space after empty cells if ($cellContent > '') $cellContent .= ' '; + + // Continue processing $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + + // Add space after empty cells if ($cellContent > '') $cellContent .= ' '; // Set the styling - if (isset($this->_formats[$child->nodeName])) { - $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + if (isset($this->_formats[$child->nodeName])) + { + $sheet->getStyle($column.$row) + ->applyFromArray($this->_formats[$child->nodeName]); } -// echo 'END OF STYLING, SPAN OR DIV
'; break; + + // Horizontal rules case 'hr' : + + // Flush the cell $this->_flushCell($sheet,$column,$row,$cellContent); + + // count ++$row; - if (isset($this->_formats[$child->nodeName])) { + + // Set the styling + if (isset($this->_formats[$child->nodeName])) + { $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); - } else { + } + // If not, enter cell content + else + { $cellContent = '----------'; $this->_flushCell($sheet,$column,$row,$cellContent); } + ++$row; + + // Linebreaks case 'br' : - if ($this->_tableLevel > 0) { - // If we're inside a table, replace with a \n + + // Add linebreak + if ($this->_tableLevel > 0) + { $cellContent .= "\n"; - } else { - // Otherwise flush our existing content and move the row cursor on + } + + // Otherwise flush our existing content and move the row cursor on + else + { $this->_flushCell($sheet,$column,$row,$cellContent); ++$row; } -// echo 'HARD LINE BREAK: ' , '
'; + break; + + // Hyperlinks case 'a' : -// echo 'START OF HYPERLINK: ' , '
'; - foreach($attributeArray as $attributeName => $attributeValue) { - switch($attributeName) { + + foreach($attributeArray as $attributeName => $attributeValue) + { + switch($attributeName) + { case 'href': -// echo 'Link to ' , $attributeValue , '
'; - $sheet->getCell($column.$row)->getHyperlink()->setUrl($attributeValue); - if (isset($this->_formats[$child->nodeName])) { + // Set the url + $sheet->getCell($column.$row) + ->getHyperlink() + ->setUrl($attributeValue); + + // Set styling + if (isset($this->_formats[$child->nodeName])) + { $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); } + break; } } + + // Add empty space $cellContent .= ' '; $this->_processDomElement($child,$sheet,$row,$column,$cellContent); -// echo 'END OF HYPERLINK:' , '
'; + break; + + // Headings/paragraphs and lists case 'h1' : case 'h2' : case 'h3' : @@ -340,30 +416,31 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, case 'ul' : case 'p' : - if ($this->_tableLevel > 0) { - // If we're inside a table, replace with a \n + if ($this->_tableLevel > 0) + { $cellContent .= "\n"; -// echo 'LIST ENTRY: ' , '
'; $this->_processDomElement($child,$sheet,$row,$column,$cellContent); - $this->_flushCell($sheet,$column,$row,$cellContent); - if (isset($this->_formats[$child->nodeName])) { + // Set style + if (isset($this->_formats[$child->nodeName])) + { $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); } - -// echo 'END OF LIST ENTRY:' , '
'; - } else { - if ($cellContent > '') { + } + else + { + if ($cellContent > '') + { $this->_flushCell($sheet,$column,$row,$cellContent); $row += 2; } -// echo 'START OF PARAGRAPH: ' , '
'; $this->_processDomElement($child,$sheet,$row,$column,$cellContent); -// echo 'END OF PARAGRAPH:' , '
'; $this->_flushCell($sheet,$column,$row,$cellContent); - if (isset($this->_formats[$child->nodeName])) { + // Set style + if (isset($this->_formats[$child->nodeName])) + { $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); } @@ -371,52 +448,75 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, $column = 'A'; } break; + + // List istem case 'li' : - if ($this->_tableLevel > 0) { + + if ($this->_tableLevel > 0) + { // If we're inside a table, replace with a \n $cellContent .= "\n"; -// echo 'LIST ENTRY: ' , '
'; $this->_processDomElement($child,$sheet,$row,$column,$cellContent); -// echo 'END OF LIST ENTRY:' , '
'; - } else { - if ($cellContent > '') { + } + else + { + if ($cellContent > '') + { $this->_flushCell($sheet,$column,$row,$cellContent); } + ++$row; -// echo 'LIST ENTRY: ' , '
'; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); -// echo 'END OF LIST ENTRY:' , '
'; $this->_flushCell($sheet,$column,$row,$cellContent); $column = 'A'; } break; + + // Tables case 'table' : + + // Flush the cells $this->_flushCell($sheet,$column,$row,$cellContent); + + // Set the start column $column = $this->_setTableStartColumn($column); -// echo 'START OF TABLE LEVEL ' , $this->_tableLevel , '
'; + if ($this->_tableLevel > 1) --$row; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); -// echo 'END OF TABLE LEVEL ' , $this->_tableLevel , '
'; + + // Release the table start column $column = $this->_releaseTableStartColumn(); - if ($this->_tableLevel > 1) { + + if ($this->_tableLevel > 1) + { ++$column; - } else { + } else + { ++$row; } + break; + + // Heading and body case 'thead' : case 'tbody' : $this->_processDomElement($child,$sheet,$row,$column,$cellContent); break; + + // Table rows case 'tr' : + + // Get start column $column = $this->_getTableStartColumn(); + + // Set empty cell content $cellContent = ''; -// echo 'START OF TABLE ' , $this->_tableLevel , ' ROW
'; + + // Continue processing $this->_processDomElement($child,$sheet,$row,$column,$cellContent); -// echo 'END OF TABLE ' , $this->_tableLevel , ' ROW
'; -// -// Count the rows after the element was parsed // If we have a rowspan, count the right amount of rows, else just 1 for($i = 0; $i < $this->spanHeight; $i++) @@ -428,7 +528,11 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, $this->spanHeight = 1; break; + + // Table heading case 'th' : + + // Continue processing $this->_processHeadings($child, $sheet, $row, $column, $cellContent); // If we have a colspan, count the right amount of columns, else just 1 @@ -441,10 +545,11 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, $this->spanWidth = 1; break; + + // Table cell case 'td' : -// echo 'START OF TABLE ' , $this->_tableLevel , ' CELL
'; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); -// echo 'END OF TABLE ' , $this->_tableLevel , ' CELL
'; $this->_flushCell($sheet,$column,$row,$cellContent); // If we have a colspan, count the right amount of columns, else just 1 @@ -457,6 +562,8 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, $this->spanWidth = 1; break; + + // Html Body case 'body' : $row = 1; $column = 'A'; @@ -464,6 +571,8 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, $this->_tableLevel = 0; $this->_processDomElement($child,$sheet,$row,$column,$cellContent); break; + + // Default default: $this->_processDomElement($child,$sheet,$row,$column,$cellContent); } @@ -471,42 +580,69 @@ private function _processDomElement(\DOMNode $element, $sheet, &$row, &$column, } } - // Data Array used for testing only, should write to PHPExcel object on completion of tests - private $_dataArray = array(); - - private $_tableLevel = 0; - private $_nestedColumn = array('A'); + /** + * Set the start column + * @param [type] $column [description] + */ + private function _setTableStartColumn($column) + { - private function _setTableStartColumn($column) { + // Set to a if ($this->_tableLevel == 0) $column = 'A'; + ++$this->_tableLevel; + + // Get nested column $this->_nestedColumn[$this->_tableLevel] = $column; return $this->_nestedColumn[$this->_tableLevel]; } - private function _getTableStartColumn() { + /** + * Get the table start clumn + * @return [type] [description] + */ + private function _getTableStartColumn() + { return $this->_nestedColumn[$this->_tableLevel]; } - private function _releaseTableStartColumn() { + /** + * Release the table start column + * @return [type] [description] + */ + private function _releaseTableStartColumn() + { --$this->_tableLevel; return array_pop($this->_nestedColumn); } - private function _flushCell($sheet,$column,$row,&$cellContent) { - if (is_string($cellContent)) { + /** + * Flush the cells + * @param [type] $sheet [description] + * @param [type] $column [description] + * @param [type] $row [description] + * @param [type] $cellContent [description] + * @return [type] [description] + */ + private function _flushCell($sheet,$column,$row,&$cellContent) + { + + if (is_string($cellContent)) + { // Simple String content - if (trim($cellContent) > '') { + if (trim($cellContent) > '') + { // Only actually write it if there's content in the string -// echo 'FLUSH CELL: ' , $column , $row , ' => ' , $cellContent , '
'; // Write to worksheet to be done here... // ... we return the cell so we can mess about with styles more easily $cell = $sheet->setCellValue($column.$row,$cellContent,true); $this->_dataArray[$row][$column] = $cellContent; } - } else { + } + else + { // We have a Rich Text run // TODO $this->_dataArray[$row][$column] = 'RICH TEXT: ' . $cellContent; @@ -823,6 +959,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) } break; + // Text align case 'text-align': $horizontal = false; @@ -853,6 +990,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) break; + // Vertical align case 'vertical-align': $vertical = false; @@ -883,6 +1021,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) ); break; + // Borders case 'border': case 'borders': $borders = explode(' ', $value); @@ -896,6 +1035,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) ); break; + // Border-top case 'border-top': $borders = explode(' ', $value); $style = $borders[1]; @@ -909,6 +1049,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) ); break; + // Border-bottom case 'border-bottom': $borders = explode(' ', $value); $style = $borders[1]; @@ -921,6 +1062,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) ); break; + // Border-right case 'border-right': $borders = explode(' ', $value); $style = $borders[1]; @@ -933,6 +1075,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) ); break; + // Border-left case 'border-left': $borders = explode(' ', $value); $style = $borders[1]; @@ -965,9 +1108,13 @@ public function getColor($color) } + /** + * Get the border style + * @param [type] $style [description] + * @return [type] [description] + */ public function borderStyle($style) { - switch($style) { case 'solid'; return PHPExcel_Style_Border::BORDER_THIN; From 2f87ecbf9bab48c6db5ed5fa7338e99ed632b5fb Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 18:14:28 +0000 Subject: [PATCH 0043/1332] Small bugfixes --- src/Maatwebsite/Excel/Readers/LaravelExcelReader.php | 5 +++-- src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php | 11 +++++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 8ec49e909..89f900a03 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -1,5 +1,6 @@ remembered) { // Return cached results - return \Cache::remember(md5($this->file), $this->cacheMinutes, function() use (&$columns) { + return Cache::remember(md5($this->file), $this->cacheMinutes, function() use (&$columns) { $this->_parseFile($columns); return $this->parsed; }); @@ -597,7 +598,7 @@ protected function _setReaderDefaults() $this->calculate = Config::get('excel::import.calculate', true); // Set default for ignoring empty cells - $this->calculate = Config::get('excel::import.ignoreEmpty', true); + $this->ignoreEmpty = Config::get('excel::import.ignoreEmpty', true); // Set default date format $this->dateFormat = Config::get('excel::import.dates.format', 'Y-m-d'); diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index efd4fb21f..4d08aceff 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -242,9 +242,6 @@ public function download() */ public function store($ext = 'xls', $path = false, $returnInfo = false) { - // Set default return Info - $returnInfo = $returnInfo ? $returnInfo : Config::get('excel::export.store.returnInfo', false); - // Set the storage path $this->_setStoragePath($path); @@ -261,7 +258,7 @@ public function store($ext = 'xls', $path = false, $returnInfo = false) $this->writer->save($toStore); // Return file info - if($returnInfo) + if($this->returnInfo($returnInfo)) { // Send back information about the stored file return array( @@ -278,6 +275,12 @@ public function store($ext = 'xls', $path = false, $returnInfo = false) return $this; } + // Check if we want to return info or itself + public function returnInfo($returnInfo = false) + { + return $returnInfo ? $returnInfo : Config::get('excel::export.store.returnInfo', false); + } + /** * Store the excel file to the server * @param str $ext The file extension From c3734f142cc4ce8e507dd1c9ca426bd9a75a2dfd Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 18:47:39 +0000 Subject: [PATCH 0044/1332] Make value encoding optional. With correct meta-charset, UTF-8 will suffice in most cases --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 33 ++++++++++++++++--- .../Excel/Readers/LaravelExcelReader.php | 6 ++-- .../Excel/Writers/LaravelExcelWriter.php | 12 ++++++- src/config/csv.php | 31 +++++++++++++++++ src/config/import.php | 18 +++------- 5 files changed, 80 insertions(+), 20 deletions(-) create mode 100644 src/config/csv.php diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 8e8d64acd..e8ab268cc 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -288,7 +288,7 @@ protected function parseCell($index) elseif($this->reader->needsCalculation()) { // Get calculated value - return $this->cell->getCalculatedValue(); + return $this->getCalculatedValue(); } else { @@ -303,11 +303,36 @@ protected function parseCell($index) */ protected function getCellValue() { - // get the value $value = $this->cell->getValue(); + return $this->encode($value); + } + + /** + * Get the calculated value + * @return [type] [description] + */ + protected function getCalculatedValue() + { + $value = $this->cell->getCalculatedValue(); + return $this->encode($value); + } + + /** + * Encode with iconv + * @param [type] $value [description] + * @return [type] [description] + */ + protected function encode($value) + { + // Get input and output encoding + list($input, $output) = array_values(Config::get('excel::import.encoding', array('UTF-8', 'UTF-8'))); + + // If they are the same, return the value + if($input == $output) + return $value; - // return encoded string - return iconv(Config::get('excel::import.encoding', 'UTF-8'), 'CP1252', $value); + // Encode + return iconv($input, $ouput, $value); } /** diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 89f900a03..5ef90eeee 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -590,8 +590,10 @@ protected function _setReaderDefaults() // Set CSV delimiter if($this->format == 'CSV') { - $this->reader->setDelimiter(Config::get('excel::import.delimiter', ',')); - $this->reader->setInputEncoding(Config::get('excel::import.encoding', 'UTF-8')); + $this->reader->setDelimiter(Config::get('excel::csv.delimiter', ',')); + $this->reader->setInputEncoding(Config::get('excel::import.encoding.input', 'UTF-8')); + $this->reader->setEnclosure(Config::get('excel::csv.enclosure', '')); + $this->reader->setLineEnding(Config::get('excel::csv.line_ending', "\r\n")); } // Set default calculate diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 4d08aceff..c86956db9 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -366,7 +366,17 @@ protected function _setFormat() */ protected function _setWriter() { - return $this->writer = \PHPExcel_IOFactory::createWriter($this->excel, $this->format); + $this->writer = \PHPExcel_IOFactory::createWriter($this->excel, $this->format); + + // Set CSV delimiter + if($this->format == 'CSV') + { + $this->writer->setDelimiter(Config::get('excel::csv.delimiter', ',')); + $this->writer->setEnclosure(Config::get('excel::csv.enclosure', '')); + $this->writer->setLineEnding(Config::get('excel::csv.line_ending', "\r\n")); + } + + return $this->writer; } /** diff --git a/src/config/csv.php b/src/config/csv.php new file mode 100644 index 000000000..1e4365c72 --- /dev/null +++ b/src/config/csv.php @@ -0,0 +1,31 @@ + ',', + + /* + |-------------------------------------------------------------------------- + | Enclosure + |-------------------------------------------------------------------------- + */ + + 'enclosure' => '', + + /* + |-------------------------------------------------------------------------- + | Line endings + |-------------------------------------------------------------------------- + */ + + 'line_ending' => "\r\n" +); \ No newline at end of file diff --git a/src/config/import.php b/src/config/import.php index 04db8d172..58dbf0f19 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -26,24 +26,16 @@ /* |-------------------------------------------------------------------------- - | Input encoding + | Import encoding |-------------------------------------------------------------------------- */ - 'encoding' => 'UTF-8', + 'encoding' => array( - /* - |-------------------------------------------------------------------------- - | Delimiter - |-------------------------------------------------------------------------- - | - | The default delimiter which will be used to read out a CSV file - | If you would like to use an other delimiter only one time, - | you can also use the `setDelimiter()` chain. - | - */ + 'input' => 'UTF-8', + 'output' => 'UTF-8' - 'delimiter' => ',', + ), /* |-------------------------------------------------------------------------- From 8d6f87f02079f1ab00f13acf64d0c60d802a53fd Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 20:12:15 +0000 Subject: [PATCH 0045/1332] Cell caching --- src/Maatwebsite/Excel/Classes/Cache.php | 116 ++++++++++++++++++ .../Excel/ExcelServiceProvider.php | 14 +++ .../Excel/Readers/LaravelExcelReader.php | 2 + src/config/cache.php | 49 ++++++++ 4 files changed, 181 insertions(+) create mode 100644 src/Maatwebsite/Excel/Classes/Cache.php create mode 100644 src/config/cache.php diff --git a/src/Maatwebsite/Excel/Classes/Cache.php b/src/Maatwebsite/Excel/Classes/Cache.php new file mode 100644 index 000000000..bc3907350 --- /dev/null +++ b/src/Maatwebsite/Excel/Classes/Cache.php @@ -0,0 +1,116 @@ + 'cache_in_memory', + 'gzip' => 'cache_in_memory_gzip', + 'serialized' => 'cache_in_memory_serialized', + 'igbinary' => 'cache_igbinary', + 'discISAM' => 'cache_to_discISAM', + 'apc' => 'cache_to_apc', + 'memcache' => 'cache_to_memcache', + 'temp' => 'cache_to_phpTemp', + 'wincache' => 'cache_to_wincache', + 'sqlite' => 'cache_to_sqlite', + 'sqlite3' => 'cache_to_sqlite3' + ); + + /** + * The name of the config file + * @var string + */ + private $configName = 'excel::cache'; + + /** + * Cache constructor + */ + public function __construct() + { + // Get driver and settings from the config + $this->driver = Config::get($this->configName . '.driver', 'memory'); + $this->settings = Config::get($this->configName . '.settings', array()); + + // Init if caching is enabled + if($this->isEnabled()) + $this->init(); + } + + /** + * Init the cache + * @return [type] [description] + */ + public function init() + { + // Find the cache driver + $this->findDriver(); + + // Set the storage driver + PHPExcel_Settings::setCacheStorageMethod($this->method, $this->settings); + } + + /** + * Set the right driver + */ + public function findDriver() + { + $property = $this->detect(); + $this->method = constant($this->class.'::'.$property); + } + + /** + * Detect the caching driver + * @return [type] [description] + */ + protected function detect() + { + // Add additional settings + $this->addAdditionalSettings(); + + // return the driver + return isset($this->available[$this->driver]) ? $this->available[$this->driver] : reset($this->available); + } + + /** + * Add additional settings for the current driver + */ + protected function addAdditionalSettings() + { + switch($this->driver) + { + case 'memcache': + + // Add extra memcache settings + $this->settings = array_merge($this->settings, array( + 'memcacheServer' => Config::get($this->configName . '.memcache.host', 'localhost'), + 'memcachePort' => Config::get($this->configName . '.memcache.port', 11211) + )); + + break; + } + } + + /** + * Check if caching is enabled + * @return boolean [description] + */ + public function isEnabled() + { + return Config::get($this->configName . '.enable', true) ? true : false; + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index f698e674c..909e8ebf5 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -1,5 +1,6 @@ app['phpexcel'] = $this->app->share(function($app) { + + // Set the caching settings + $this->setCacheSettings(); + + // Init phpExcel return new PHPExcel(); }); } @@ -123,6 +129,14 @@ protected function bindExcel() }); } + /** + * Set the cache settings + */ + protected function setCacheSettings() + { + return new Cache(); + } + /** * Get the services provided by the provider. * diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 5ef90eeee..dcf4ba67a 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -169,6 +169,8 @@ public function load($file) // Load the file $this->excel = $this->reader->load($this->file); + dd($this->excel); + // Return itself return $this; } diff --git a/src/config/cache.php b/src/config/cache.php new file mode 100644 index 000000000..9c44f421b --- /dev/null +++ b/src/config/cache.php @@ -0,0 +1,49 @@ + true, + + /* + |-------------------------------------------------------------------------- + | Caching driver + |-------------------------------------------------------------------------- + | + | Set the caching driver + | + | Available methods: + | memory|gzip|serialized|igbinary|discISAM|apc|memcache|temp|wincache|sqlite|sqlite3 + | + */ + 'driver' => 'memory', + + /* + |-------------------------------------------------------------------------- + | Cache settings + |-------------------------------------------------------------------------- + */ + 'settings' => array( + + 'memoryCacheSize' => '32MB', + 'cacheTime' => 600 + + ), + + /* + |-------------------------------------------------------------------------- + | Memcache settings + |-------------------------------------------------------------------------- + */ + 'memcache' => array( + + 'host' => 'localhost', + 'port' => 11211, + + ) + +); \ No newline at end of file From ac91310836b9e0dd86cd6128ea11468ac1038d23 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 20:15:09 +0000 Subject: [PATCH 0046/1332] Set locale based on app.locale --- src/Maatwebsite/Excel/ExcelServiceProvider.php | 14 ++++++++++++++ .../Excel/Readers/LaravelExcelReader.php | 2 -- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 909e8ebf5..edfd665e4 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -1,5 +1,7 @@ app['phpexcel'] = $this->app->share(function($app) { + // Set locale + $this->setLocale(); + // Set the caching settings $this->setCacheSettings(); @@ -137,6 +142,15 @@ protected function setCacheSettings() return new Cache(); } + /** + * Set locale + */ + protected function setLocale() + { + $locale = Config::get('app.locale', 'en_us'); + PHPExcel_Settings::setLocale($locale); + } + /** * Get the services provided by the provider. * diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index dcf4ba67a..5ef90eeee 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -169,8 +169,6 @@ public function load($file) // Load the file $this->excel = $this->reader->load($this->file); - dd($this->excel); - // Return itself return $this; } From 1882a160a2231de03a1b6133174d07ae3791d9e8 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 20:19:53 +0000 Subject: [PATCH 0047/1332] Added cache dir config for dicsISAM --- src/Maatwebsite/Excel/Classes/Cache.php | 9 +++++++++ src/config/cache.php | 12 ++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/Cache.php b/src/Maatwebsite/Excel/Classes/Cache.php index bc3907350..0c47ddf08 100644 --- a/src/Maatwebsite/Excel/Classes/Cache.php +++ b/src/Maatwebsite/Excel/Classes/Cache.php @@ -100,6 +100,15 @@ protected function addAdditionalSettings() 'memcachePort' => Config::get($this->configName . '.memcache.port', 11211) )); + break; + + case 'discISAM': + + // Add dir + $this->settings = array_merge($this->settings, array( + 'dir' => Config::get($this->configName . '.dir', storage_path('cache')), + )); + break; } } diff --git a/src/config/cache.php b/src/config/cache.php index 9c44f421b..f55daa1c2 100644 --- a/src/config/cache.php +++ b/src/config/cache.php @@ -20,7 +20,7 @@ | memory|gzip|serialized|igbinary|discISAM|apc|memcache|temp|wincache|sqlite|sqlite3 | */ - 'driver' => 'memory', + 'driver' => 'discISAM', /* |-------------------------------------------------------------------------- @@ -44,6 +44,14 @@ 'host' => 'localhost', 'port' => 11211, - ) + ), + + /* + |-------------------------------------------------------------------------- + | Cache dir (for discISAM) + |-------------------------------------------------------------------------- + */ + + 'dir' => storage_path('cache') ); \ No newline at end of file From 6cb8a6a2fe573ee99269cb7c2b7b35f300f40807 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 20:42:25 +0000 Subject: [PATCH 0048/1332] composer.json psr-0 fix + added phpunit.xml --- composer.json | 2 +- phpunit.xml | 18 ++++++++++++++++++ tests/.gitkeep | 0 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 phpunit.xml create mode 100644 tests/.gitkeep diff --git a/composer.json b/composer.json index b183de9ee..f17a67927 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,7 @@ "src/Maatwebsite/Excel" ], "psr-0": { - "Maatwebsite\\Excel": "src/" + "Maatwebsite\\Excel\\": "src/" } }, "minimum-stability": "stable" diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 000000000..3347b75b7 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,18 @@ + + + + + ./tests/ + + + diff --git a/tests/.gitkeep b/tests/.gitkeep new file mode 100644 index 000000000..e69de29bb From a3c0e7375013d1e6ebcb9d60f9bad0fe51f35688 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 22:59:28 +0000 Subject: [PATCH 0049/1332] First unit tests --- composer.json | 4 + src/Maatwebsite/Excel/Classes/PHPExcel.php | 3 +- .../Excel/ExcelServiceProvider.php | 2 +- src/Maatwebsite/Excel/Readers/Batch.php | 8 +- .../Excel/Writers/LaravelExcelWriter.php | 9 +- tests/Excel/ExcelTestCase.php | 108 ++++++++++++++++++ tests/Excel/ExcelTester.php | 67 +++++++++++ 7 files changed, 187 insertions(+), 14 deletions(-) create mode 100644 tests/Excel/ExcelTestCase.php create mode 100644 tests/Excel/ExcelTester.php diff --git a/composer.json b/composer.json index f17a67927..227f11b9d 100644 --- a/composer.json +++ b/composer.json @@ -16,6 +16,10 @@ "illuminate/filesystem": "4.x", "phpoffice/phpexcel": "1.8.*" }, + "require-dev": { + "mockery/mockery": "0.9.*", + "phpunit/phpunit": "4.0.*" + }, "autoload": { "classmap": [ "src/Maatwebsite/Excel" diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index 33ba12e18..8d69e2c77 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -1,5 +1,6 @@ app['excel'] = $this->app->share(function($app) { - return new Excel($app['phpexcel'], $app['excel.reader'], $app['excel.writer'], $app['excel.parsers.view'], $app['config'], $app['view'], $app['files']); + return new Excel($app['phpexcel'], $app['excel.reader'], $app['excel.writer'], $app['excel.parsers.view']); }); } diff --git a/src/Maatwebsite/Excel/Readers/Batch.php b/src/Maatwebsite/Excel/Readers/Batch.php index c3a6aa8ab..d52ff94ca 100644 --- a/src/Maatwebsite/Excel/Readers/Batch.php +++ b/src/Maatwebsite/Excel/Readers/Batch.php @@ -40,15 +40,15 @@ class Batch { ); /** - * Constructor - * @param [type] $files [description] + * Start the batch + * @return [type] [description] */ - public function __construct(Excel $excel, $files, Closure $callback) + public function start(Excel $excel, $files, Closure $callback) { // Set excel object $this->excel = $excel; - // Set files + // Set files $this->_setFiles($files); // Do the callback diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index c86956db9..41790fb72 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -455,13 +455,6 @@ public function __call($method, $params) } - /** - * On destruct - */ - public function __destruct() - { - $this->excel->disconnectWorksheets(); - unset($this->excel); - } + } \ No newline at end of file diff --git a/tests/Excel/ExcelTestCase.php b/tests/Excel/ExcelTestCase.php new file mode 100644 index 000000000..c050f06b2 --- /dev/null +++ b/tests/Excel/ExcelTestCase.php @@ -0,0 +1,108 @@ +setMocks(); + + // Init our excel class + $this->excel = new Excel($this->phpexcel, $this->reader, $this->writer); + } + + /** + * Test the constructor + * @return [type] [description] + */ + public function testConstructor() + { + $this->assertInstanceOf('Maatwebsite\Excel\Excel', $this->excel); + } + + /** + * Set the mocks + */ + public function setMocks() + { + $this->mockPHPExcel(); + $this->mockReader(); + $this->mockWriter(); + $this->mockBatch(); + } + + /** + * Mock PHPExcel class + * @return [type] [description] + */ + public function mockPHPExcel() + { + $this->phpexcel = m::mock('Maatwebsite\Excel\Classes\PHPExcel'); + $this->phpexcel->shouldReceive('getID'); + $this->phpexcel->shouldReceive('disconnectWorksheets'); + $this->phpexcel->shouldReceive('setDefaultProperties'); + } + + /** + * Mock Reader class + * @return [type] [description] + */ + public function mockReader() + { + $this->reader = m::mock('Maatwebsite\Excel\Readers\LaravelExcelReader'); + $this->reader->shouldReceive('injectExcel')->with($this->phpexcel); + $this->reader->shouldReceive('load'); + $this->reader->shouldReceive('setSelectedSheets'); + } + + /** + * Mock Writer class + * @return [type] [description] + */ + public function mockWriter() + { + $this->writer = m::mock('Maatwebsite\Excel\Writers\LaravelExcelWriter'); + $this->writer->shouldReceive('injectExcel')->with($this->phpexcel); + $this->writer->shouldReceive('setTitle'); + $this->writer->shouldReceive('shareView')->andReturn($this->writer); + } + + /** + * Mock Writer class + * @return [type] [description] + */ + public function mockBatch() + { + $this->batch = m::mock('Maatwebsite\Excel\Readers\Batch'); + $this->batch->shouldReceive('start')->andReturn('foo'); + } + + /** + * Teardown + * @return [type] [description] + */ + public function tearDown() + { + m::close(); + } + +} \ No newline at end of file diff --git a/tests/Excel/ExcelTester.php b/tests/Excel/ExcelTester.php new file mode 100644 index 000000000..f08f18d4b --- /dev/null +++ b/tests/Excel/ExcelTester.php @@ -0,0 +1,67 @@ +excel->create('test', function() {}); + $this->assertEquals($this->writer, $created); + } + + /** + * Test load + * @return [type] [description] + */ + public function testLoad() + { + $loaded = $this->excel->load('test.csv', function() {}); + $this->assertEquals($this->reader, $loaded); + } + + /** + * Test select sheets + * @return [type] [description] + */ + public function testSelectSheets() + { + $selected = $this->excel->selectSheets(array('sheet')); + $this->assertEquals($this->excel, $selected); + } + + /** + * Test a batch + * @return [type] [description] + */ + public function testBatch() + { + $loaded = $this->excel->batch(array('file'), function() {}); + $this->assertInstanceOf('Maatwebsite\Excel\Readers\Batch', $loaded); + } + + /** + * Test the share view + * @return [type] [description] + */ + public function testShareView() + { + $selected = $this->excel->shareView('filename', array('test'), array('test')); + $this->assertEquals($this->writer, $selected); + } + + /** + * Test load view + * @return [type] [description] + */ + public function testLoadView() + { + $selected = $this->excel->loadView('filename', array('test'), array('test')); + $this->assertEquals($this->writer, $selected); + } + +} \ No newline at end of file From a040f93f7db9d7c51d9cb4caf5be943f74331355 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 10 May 2014 23:06:18 +0000 Subject: [PATCH 0050/1332] Added travis.yml --- .travis.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..f0d36ff27 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,12 @@ +language: php + +php: + - 5.3 + - 5.4 + - 5.5 + +before_script: + - curl -s http://getcomposer.org/installer | php + - php composer.phar install --dev + +script: phpunit \ No newline at end of file From ebb9402eac73c70919bd2464024243a14227f112 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Sun, 11 May 2014 01:16:03 +0200 Subject: [PATCH 0051/1332] Update README.md --- README.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 777e3a38d..82f761876 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,15 @@ ## Laravel 4 Wrapper for PHPExcel v0.4.0 - DEV -[![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![Latest Unstable Version](https://poser.pugx.org/maatwebsite/excel/v/unstable.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) -[![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) +[![Latest Stable Version(https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) + +[![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) + +[![Build Status](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel.svg?branch=develop)](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel) + +[![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) + +[![Monthly Downloads(https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) + [![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) #New to v0.3.x From 5f02813fe534531e71c713f1696a9b0b42f6dafb Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Sun, 11 May 2014 01:23:08 +0200 Subject: [PATCH 0052/1332] Added travis badge --- README.md | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 82f761876..624d44801 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,9 @@ ## Laravel 4 Wrapper for PHPExcel v0.4.0 - DEV -[![Latest Stable Version(https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) - -[![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) - [![Build Status](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel.svg?branch=develop)](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel) - -[![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) - -[![Monthly Downloads(https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) - +[![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) +[![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) [![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) - #New to v0.3.x - Possibility to call **all native PHPExcel methods** - seperator config value for label formatting (default is `-`) From f47cfd8f70e97747999d8070cd78aca2a4af7cd4 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 11 May 2014 20:23:35 +0000 Subject: [PATCH 0053/1332] Added first docs --- docs/export.md | 4 +++ docs/export/array.md | 16 +++++++++ docs/export/sheet-styling.md | 23 +++++++++++++ docs/export/sheets.md | 50 ++++++++++++++++++++++++++++ docs/export/simple.md | 33 ++++++++++++++++++ docs/getting-started.md | 4 +++ docs/getting-started/config.md | 8 +++++ docs/getting-started/contributing.md | 22 ++++++++++++ docs/getting-started/installation.md | 17 ++++++++++ docs/getting-started/license.md | 3 ++ docs/import.md | 0 11 files changed, 180 insertions(+) create mode 100644 docs/export.md create mode 100644 docs/export/array.md create mode 100644 docs/export/sheet-styling.md create mode 100644 docs/export/sheets.md create mode 100644 docs/export/simple.md create mode 100644 docs/getting-started.md create mode 100644 docs/getting-started/config.md create mode 100644 docs/getting-started/contributing.md create mode 100644 docs/getting-started/installation.md create mode 100644 docs/getting-started/license.md create mode 100644 docs/import.md diff --git a/docs/export.md b/docs/export.md new file mode 100644 index 000000000..c68b6f0db --- /dev/null +++ b/docs/export.md @@ -0,0 +1,4 @@ +@include:Creating a new file|simple +@include:Creating Sheets|sheets +@include:Creatings Sheets From array|array +@include:Sheet styling|sheet-styling \ No newline at end of file diff --git a/docs/export/array.md b/docs/export/array.md new file mode 100644 index 000000000..027bc4fa6 --- /dev/null +++ b/docs/export/array.md @@ -0,0 +1,16 @@ +# Creating a file from an array + +To create a new file from an array use `->fromArray()` inside the sheet closure: + + Excel::create('Filename', function($excel) { + + $excel->sheet('Sheetname', function($sheet) { + + $sheet->fromArray(array( + array('data1', 'data2'), + array('data3', 'data4') + )); + + }); + + })->export('xls'); \ No newline at end of file diff --git a/docs/export/sheet-styling.md b/docs/export/sheet-styling.md new file mode 100644 index 000000000..ff9cf1582 --- /dev/null +++ b/docs/export/sheet-styling.md @@ -0,0 +1,23 @@ +# Styling sheets + +### Fonts + +To change the font for the current sheet use `->setFont($array)`: + + $sheet->setFont(array( + 'family' => 'Calibri', + 'size' => '15', + 'bold' => true + )); + +#### Font Family + + $sheet->setFontFamily('Comic Sans MS'); + +#### Font Size + + $sheet->setFontSize(15); + +#### Bold + + $sheet->setFontBold(true); \ No newline at end of file diff --git a/docs/export/sheets.md b/docs/export/sheets.md new file mode 100644 index 000000000..b7267b2a3 --- /dev/null +++ b/docs/export/sheets.md @@ -0,0 +1,50 @@ +# Sheets + +### Creating a sheet + +To create a new sheet inside our newly created file, use `->sheets('Sheetname')`: + + Excel::create('Filename', function($excel) { + + $excel->sheet('Sheetname', function($sheet) { + + // sheet manipulation + + }); + + })->export('xls'); + + +### Creating multiple sheets + + You can set as many sheets as you like inside the file: + + Excel::create('Filename', function($excel) { + + // Our first sheet + $excel->sheet('First sheet', function($sheet) { + + }); + + // Our second sheet + $excel->sheet('Second sheet', function($sheet) { + + }); + + })->export('xls'); + +### Changing properties + +There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See `app/config/packages/maatwebsite/excel/config.php` + + Excel::create('Filename', function($excel) { + + $excel->sheet('Sheetname', function($sheet) { + + $sheet->setOrientation('landscape'); + + }); + + })->export('xls'); + +Go to the reference guide to see a list of available properties. \ No newline at end of file diff --git a/docs/export/simple.md b/docs/export/simple.md new file mode 100644 index 000000000..fa9e563a0 --- /dev/null +++ b/docs/export/simple.md @@ -0,0 +1,33 @@ +# Simple Excel Export + +### Basics + +A new file can be created using the `create` method with the filename as first paramater. + + Excel::create('Filename') + +To manipulate the creation of the file you can use the callback + + Excel::create('Filename', function($excel) { + + // call writer methods here + + }); + +### Changing properties + +There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See `app/config/packages/maatwebsite/excel/config.php` + + Excel::create('Filename', function($excel) { + + // Chain the setters + $excel->setCreator('Maatwebsite') + ->setCompany('Maatwebsite') + + // Call them seperatly + $excel->setDescription('A demonstration to change the file properties'); + + }); + +Go to the reference guide to see a list of available properties. + diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 000000000..3ed5e951f --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,4 @@ +@include:Installation|installation +@include:Config|config +@include:Contributing|contributing +@include:License|license \ No newline at end of file diff --git a/docs/getting-started/config.md b/docs/getting-started/config.md new file mode 100644 index 000000000..6686ae190 --- /dev/null +++ b/docs/getting-started/config.md @@ -0,0 +1,8 @@ +#Config + +Laravel Excel includes several config settings for import-, export-, view-, CSV-specific settings, +Use the artisan publish command to publish the config file to your project. + + php artisan config:publish maatwebsite/excel + +The config files can now be found at `app/config/packages/maatwebsite/excel` \ No newline at end of file diff --git a/docs/getting-started/contributing.md b/docs/getting-started/contributing.md new file mode 100644 index 000000000..f01c3c8b3 --- /dev/null +++ b/docs/getting-started/contributing.md @@ -0,0 +1,22 @@ +# Contribution Guide + +### Bug fixes + +**ALL** bug fixes should be made to the `dev-develop` branch which they belong. Bug fixes should never be sent to the `master` branch. + +### Pull Requests + +Every pull request should pass the unit tests. If you include new functionality, make sure you include a test. Pull request will be evaluated and possibly added to the next stable release. + +### Feature Requests + +If you have an idea for a new feature you would like to see added to Laravel Excel, you may create an issue on GitHub with `[Request]` in the title. The feature request will then be reviewed by @Maatwebsite. + +### Coding Guidelines + +Laravel follows the [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) and [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md) coding standards. In addition to these standards, below is a list of other coding standards that should be followed: + +- Namespace declarations should be on the same line as ` 'Maatwebsite\Excel\Facades\Excel', + +The class is binded to the ioC as `excel` + + $excel = App::make('excel'); \ No newline at end of file diff --git a/docs/getting-started/license.md b/docs/getting-started/license.md new file mode 100644 index 000000000..6d69a602c --- /dev/null +++ b/docs/getting-started/license.md @@ -0,0 +1,3 @@ +#License + +This package is licensed under LGPL. You are free to use it in personal and commercial projects. The code can be forked and modified, but original copyright author should always be included! \ No newline at end of file diff --git a/docs/import.md b/docs/import.md new file mode 100644 index 000000000..e69de29bb From 33d681759f3a0319c4699c1985a378938c0ef376 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 12 May 2014 18:49:43 +0000 Subject: [PATCH 0054/1332] Export docs + start of import docs --- docs/export.md | 11 ++++- docs/export/array.md | 11 ++++- docs/export/autofilter.md | 9 ++++ docs/export/autosize.md | 16 +++++++ docs/export/call.md | 19 ++++++++ docs/export/export.md | 26 +++++++++++ docs/export/format.md | 18 ++++++++ docs/export/freeze.md | 15 +++++++ docs/export/merge.md | 19 ++++++++ docs/export/sheet-styling.md | 28 +++++++++--- docs/export/sheets.md | 4 +- docs/export/simple.md | 10 +++-- docs/export/sizing.md | 41 ++++++++++++++++++ docs/export/store.md | 40 +++++++++++++++++ docs/import.md | 2 + docs/import/basics.md | 7 +++ docs/import/batch.md | 43 +++++++++++++++++++ .../Excel/Writers/LaravelExcelWriter.php | 14 +++++- src/config/export.php | 2 +- 19 files changed, 317 insertions(+), 18 deletions(-) create mode 100644 docs/export/autofilter.md create mode 100644 docs/export/autosize.md create mode 100644 docs/export/call.md create mode 100644 docs/export/export.md create mode 100644 docs/export/format.md create mode 100644 docs/export/freeze.md create mode 100644 docs/export/merge.md create mode 100644 docs/export/sizing.md create mode 100644 docs/export/store.md create mode 100644 docs/import/basics.md create mode 100644 docs/import/batch.md diff --git a/docs/export.md b/docs/export.md index c68b6f0db..d2408211d 100644 --- a/docs/export.md +++ b/docs/export.md @@ -1,4 +1,13 @@ @include:Creating a new file|simple +@include:Exporting|export +@include:Store to server|store @include:Creating Sheets|sheets @include:Creatings Sheets From array|array -@include:Sheet styling|sheet-styling \ No newline at end of file +@include:Sheet styling|sheet-styling +@include:Freeze rows|freeze +@include:Auto filter|autofilter +@include:Cell sizing|sizing +@include:Auto size|autosize +@include:Column merging|merge +@include:Column formatting|format +@include:PHPExcel methods|call \ No newline at end of file diff --git a/docs/export/array.md b/docs/export/array.md index 027bc4fa6..97562bcc8 100644 --- a/docs/export/array.md +++ b/docs/export/array.md @@ -1,4 +1,4 @@ -# Creating a file from an array +# Creating a sheet from an array To create a new file from an array use `->fromArray()` inside the sheet closure: @@ -13,4 +13,11 @@ To create a new file from an array use `->fromArray()` inside the sheet closure: }); - })->export('xls'); \ No newline at end of file + })->export('xls'); + +Alternativly you can use `->with()` + + $sheet->with(array( + array('data1', 'data2'), + array('data3', 'data4') + )); \ No newline at end of file diff --git a/docs/export/autofilter.md b/docs/export/autofilter.md new file mode 100644 index 000000000..00fbd818c --- /dev/null +++ b/docs/export/autofilter.md @@ -0,0 +1,9 @@ +# Auto filter + +To enable the auto filter use `->setAutoFilter($range = false)` + + // Autofilter for entire sheet + $sheet->setAutoFilter(); + + // Set auto filter for a range + $sheet->setAutoFilter('A1:E10'); \ No newline at end of file diff --git a/docs/export/autosize.md b/docs/export/autosize.md new file mode 100644 index 000000000..5fac6769f --- /dev/null +++ b/docs/export/autosize.md @@ -0,0 +1,16 @@ +# Auto size + +By default the exported file be automatically auto sized. To change this behaviour you can either change the config or use the setters: + + // Set autosize for sheet + $sheet->setAutoSize(true); + + // Disable autosize for sheet + $sheet->setAutoSize(false); + + // Disable autosize for columns + $sheet->setAutoSize(array( + 'A', 'C' + )); + +> The default config setting can be found in: `export.php` \ No newline at end of file diff --git a/docs/export/call.md b/docs/export/call.md new file mode 100644 index 000000000..3c2626d87 --- /dev/null +++ b/docs/export/call.md @@ -0,0 +1,19 @@ +# Calling PHPExcel native methods + +It's possible to call all native PHPExcel methods on the `$excel` and `$sheet` objects. + +### Calling Workbook methods + +Example: + + // Get default style for this workbook + $excel->getDefaultStyle(); + +### Calling worksheet methods + +Example: + + // Protect cells + $sheet->protectCells('A1', $password); + +> Head over to PHPOffice to learn more about the native methods. \ No newline at end of file diff --git a/docs/export/export.md b/docs/export/export.md new file mode 100644 index 000000000..c164ae9ae --- /dev/null +++ b/docs/export/export.md @@ -0,0 +1,26 @@ +# Exporting + +To download the created file, use `->export($ext)` or `->download($ext)` + +#### Export to Excel5 (xls) + + Excel::create('Filename', function($excel) { + + })->export('xls'); + + // or + ->download('xls'); + +#### Export to Excel2007 (xlsx) + + ->export('xlsx'); + + // or + ->download('xlsx'); + +#### Export to CSV + + ->export('csv'); + + // or + ->download('csv'); \ No newline at end of file diff --git a/docs/export/format.md b/docs/export/format.md new file mode 100644 index 000000000..55abd29f4 --- /dev/null +++ b/docs/export/format.md @@ -0,0 +1,18 @@ +# Column formatting + +To tell Excel how it should interpret certain columns, you can use `->setColumnFormat($array)`. + + // Format column as percentage + $sheet->setColumnFormat(array( + 'C' => '0%' + )); + + // Set multiple column formats + $sheet->setColumnFormat(array( + 'B' => '0', + 'D' => '0.00', + 'F' => '@', + 'F' => 'yyyy-mm-dd', + )); + +> Go to the reference guide to see a list of available formats. \ No newline at end of file diff --git a/docs/export/freeze.md b/docs/export/freeze.md new file mode 100644 index 000000000..fdaae1cd5 --- /dev/null +++ b/docs/export/freeze.md @@ -0,0 +1,15 @@ +# Freeze rows + +If you want to freeze a cell, row or column, use: + + // Freeze first row + $sheet->freezeFirstRow(); + + // Freeze the first column + $sheet->freezeFirstColumn(); + + // Freeze the first row and column + $sheet->freezeFirstRowAndColumn(); + + // Set freeze + $sheet->setFreeze('A2'); \ No newline at end of file diff --git a/docs/export/merge.md b/docs/export/merge.md new file mode 100644 index 000000000..70a2d4d6f --- /dev/null +++ b/docs/export/merge.md @@ -0,0 +1,19 @@ +# Column merging + +### Merging cells + +To merge a range of cells, use `->mergeCells($range)` + + $sheet->mergeCells('A1:E1'); + +### Merging columns and rows + +To merge columns and rows, use `->setMergeColumn($array)` + + $sheet->setMergeColumn(array( + 'columns' => array('A','B','C','D'), + 'rows' => array( + array(2,3), + array(5,11), + ) + )); \ No newline at end of file diff --git a/docs/export/sheet-styling.md b/docs/export/sheet-styling.md index ff9cf1582..fc3147056 100644 --- a/docs/export/sheet-styling.md +++ b/docs/export/sheet-styling.md @@ -1,4 +1,4 @@ -# Styling sheets +# Sheet styling ### Fonts @@ -10,14 +10,30 @@ To change the font for the current sheet use `->setFont($array)`: 'bold' => true )); -#### Font Family +#### Seperate setters + // Font family $sheet->setFontFamily('Comic Sans MS'); -#### Font Size - + // Font size $sheet->setFontSize(15); -#### Bold + // Font bold + $sheet->setFontBold(true); + +> Go to the reference guide to see a list of available font stylings. + +### Borders + +You can set borders for the sheet, by using: + + // Sets all borders + $sheet->setAllBorder('thin'); + + // Set border for cells + $sheet->setBorder('A1', 'thin'); + + // Set border for range + $sheet->setBorder('A1:F10', 'thin'); - $sheet->setFontBold(true); \ No newline at end of file +> Go to the reference guide to see a list of available border styles \ No newline at end of file diff --git a/docs/export/sheets.md b/docs/export/sheets.md index b7267b2a3..07bf8a123 100644 --- a/docs/export/sheets.md +++ b/docs/export/sheets.md @@ -17,7 +17,7 @@ To create a new sheet inside our newly created file, use `->sheets('Sheetname')` ### Creating multiple sheets - You can set as many sheets as you like inside the file: +You can set as many sheets as you like inside the file: Excel::create('Filename', function($excel) { @@ -47,4 +47,4 @@ There are a couple of properties we can change inside the closure. Most of them })->export('xls'); -Go to the reference guide to see a list of available properties. \ No newline at end of file +> Go to the reference guide to see a list of available properties. \ No newline at end of file diff --git a/docs/export/simple.md b/docs/export/simple.md index fa9e563a0..ef2c263f5 100644 --- a/docs/export/simple.md +++ b/docs/export/simple.md @@ -4,7 +4,7 @@ A new file can be created using the `create` method with the filename as first paramater. - Excel::create('Filename') + Excel::create('Filename'); To manipulate the creation of the file you can use the callback @@ -20,14 +20,16 @@ There are a couple of properties we can change inside the closure. Most of them Excel::create('Filename', function($excel) { + // Set the title + $excel->setTitle('Our new awesome title'); + // Chain the setters $excel->setCreator('Maatwebsite') - ->setCompany('Maatwebsite') + ->setCompany('Maatwebsite'); // Call them seperatly $excel->setDescription('A demonstration to change the file properties'); }); -Go to the reference guide to see a list of available properties. - +> Go to the reference guide to see a list of available properties. \ No newline at end of file diff --git a/docs/export/sizing.md b/docs/export/sizing.md new file mode 100644 index 000000000..3b4437a15 --- /dev/null +++ b/docs/export/sizing.md @@ -0,0 +1,41 @@ +# Cell size + +### Set column width + +To set the column width use `->setWidth($cell, $width)` + + // Set width for single column + $sheet->setWidth('A', 5); + + // Set width for multiple cells + $sheet->setWidth(array( + 'A' => 5, + 'B' => 10 + )); + +### Set row height + +To set the row height use `->setHeight($row, $height)` + + // Set height for single row + $sheet->setHeight(1, 50); + + // Set height for multiple rows + $sheet->setHeight(array( + 1 => 50, + 2 => 25 + )); + +### Set cell size + +To set the cell size use `->setSize($cell, $width, $height)` + + // Set size for single cell + $sheet->setSize('A1', 500, 50); + + $sheet->setSize(array( + 'A1' => array( + 'width' => 50 + 'height' => 500, + ) + )); \ No newline at end of file diff --git a/docs/export/store.md b/docs/export/store.md new file mode 100644 index 000000000..b50490c35 --- /dev/null +++ b/docs/export/store.md @@ -0,0 +1,40 @@ +# Store to server + +To store the created file to the server, use `->store($ext, $path = false, $returnInfo = false)` or `->save()` + +### Normal export to default storage path + +By default the file will be stored inside the `app/storage/exports` folder, which has been defined in the `export.php` config file. + + Excel::create('Filename', function($excel) { + + // Set sheets + + })->store('xls'); + +### Normal export to custom storage path + +If you want to use a custom storage path (e.g. to seperate the files per client), you can set the folder as the second parameter. + + ->store('xls', storage_path('excel/exports')); + +### Store and export + + ->store('xls')->export('xls'); + +### Store and return storage info + +If you want to return storage information, set the third paramter to true or change the config setting inside `export.php` + + ->store('xls', false, true); + + // Will return + return array( + 'full', + 'path', + 'file', + 'title', + 'ext' + ); + +> Make sure your storage folder is **writable**! \ No newline at end of file diff --git a/docs/import.md b/docs/import.md index e69de29bb..5f33133bd 100644 --- a/docs/import.md +++ b/docs/import.md @@ -0,0 +1,2 @@ +@include:Importing a file|basics +@include:Batch import|batch \ No newline at end of file diff --git a/docs/import/basics.md b/docs/import/basics.md new file mode 100644 index 000000000..4e1b17a85 --- /dev/null +++ b/docs/import/basics.md @@ -0,0 +1,7 @@ +# Importing a file + + Excel::load('file.xls', function($reader) { + + // reader methods + + }); \ No newline at end of file diff --git a/docs/import/batch.md b/docs/import/batch.md new file mode 100644 index 000000000..8089efb7a --- /dev/null +++ b/docs/import/batch.md @@ -0,0 +1,43 @@ +#Batch import + +### Import a folder + +To import an entire folder (only xls, xlsx and csv files will be used), set the folder as first parameter. + + Excel::batch('app/storage/uploads', function($rows, $file) { + + // Explain the reader how it should interpret each row, + // for every file inside the batch + $rows->each(function($row) { + + // Example: dump the firstname + dd($row->firstname); + + }); + + }); + +### Import multiple files + +It's also possible to provide an array of files to import. + + $files = array( + 'file1.xls', + 'file2.xls' + ); + + Excel::batch($files, function($rows, $file) { + + }); + +### Import a folder and multiple sheets + +When your files contain multiple sheets, you should also loop the sheets + + Excel::batch('app/storage/uploads', function($sheets, $file) { + + $sheets->each(function($sheet) { + + }); + + }); \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 41790fb72..cb14443ee 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -199,14 +199,24 @@ public function export($ext = 'xls') $this->_render(); // Download the file - $this->download(); + $this->_download(); + } + + /** + * Export and download the spreadsheet + * @param string $ext [description] + * @return [type] [description] + */ + public function download($ext = 'xls') + { + return $this->export($ext); } /** * Download a file * @return [type] [description] */ - public function download() + protected function _download() { // Set the headers $this->_setHeaders(array( diff --git a/src/config/export.php b/src/config/export.php index f968e34fb..70f0312f0 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -30,7 +30,7 @@ | */ - 'path' => base_path('app/storage/uploads'), + 'path' => base_path('app/storage/exports'), /* |-------------------------------------------------------------------------- From 8e31604d6dd5bdc75e59ff40ec2ce00d6d587fac Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Mon, 12 May 2014 20:56:40 +0200 Subject: [PATCH 0055/1332] Docs: add setColumnFormat by range --- docs/export/format.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/export/format.md b/docs/export/format.md index 55abd29f4..f3d2ada5c 100644 --- a/docs/export/format.md +++ b/docs/export/format.md @@ -6,6 +6,11 @@ To tell Excel how it should interpret certain columns, you can use `->setColumnF $sheet->setColumnFormat(array( 'C' => '0%' )); + + // Format a range with e.g. leading zeros + $sheet->setColumnFormat(array( + 'A2:K2' => '0000' + )); // Set multiple column formats $sheet->setColumnFormat(array( @@ -15,4 +20,4 @@ To tell Excel how it should interpret certain columns, you can use `->setColumnF 'F' => 'yyyy-mm-dd', )); -> Go to the reference guide to see a list of available formats. \ No newline at end of file +> Go to the reference guide to see a list of available formats. From 2abcf9efdcbe00f1d492060268b4c2619063cf84 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 14 May 2014 16:09:28 +0000 Subject: [PATCH 0056/1332] Storage fixes --- .../Excel/Writers/LaravelExcelWriter.php | 16 ++++++++-------- src/config/export.php | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index cb14443ee..519aee6ed 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -60,7 +60,7 @@ class LaravelExcelWriter { * Path the file will be stored to * @var [type] */ - public $storagePath = 'app/storage/uploads'; + public $storagePath = 'exports'; /** * Header Content-type @@ -103,6 +103,7 @@ public function injectExcel($excel) public function setTitle($title) { $this->title = $title; + return $this; } /** @@ -409,12 +410,9 @@ protected function _setHeaders($headers) protected function _setStoragePath($path = false) { // Get the default path - $path = $path ? $path : Config::get('excel::export.store.path', base_path($this->storagePath)); - - if(!realpath($path)) - $path = base_path($path); + $path = $path ? $path : Config::get('excel::export.store.path', storage_path($this->storagePath)); - // Trim of slashes, to makes sure we won't add them double + // Trim of slashes, to makes sure we won't add them double $this->storagePath = rtrim($path, '/'); // Make sure the storage path exists @@ -444,14 +442,16 @@ public function __call($method, $params) if(method_exists($this->excel, $method)) { // Call the method from the excel object with the given params - return call_user_func_array(array($this->excel, $method), $params); + call_user_func_array(array($this->excel, $method), $params); + return $this; } // Call a php excel sheet method elseif(method_exists($this->excel->getActiveSheet(), $method)) { // Call the method from the excel object with the given params - return call_user_func_array(array($this->excel->getActiveSheet(), $method), $params); + call_user_func_array(array($this->excel->getActiveSheet(), $method), $params); + return $this; } // If the dynamic call starts with "with", add the var to the data array diff --git a/src/config/export.php b/src/config/export.php index 70f0312f0..39229e373 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -30,7 +30,7 @@ | */ - 'path' => base_path('app/storage/exports'), + 'path' => storage_path('exports'), /* |-------------------------------------------------------------------------- From 34ec9154a08505e818c0cdcf81f801cd76c9bbc7 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 14 May 2014 18:03:49 +0000 Subject: [PATCH 0057/1332] Added ->select() method to select columns --- src/Maatwebsite/Excel/Excel.php | 2 +- .../Excel/Readers/LaravelExcelReader.php | 23 ++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 75b1edcc2..4b0b7e38d 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -102,7 +102,7 @@ public function load($file, $callback = false) // Do the callback if($callback instanceof Closure) - call_user_func($callback, $this->reader); + call_user_func($callback, $this->reader; // Return the reader object return $this->reader; diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 5ef90eeee..c04c33660 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -38,6 +38,12 @@ class LaravelExcelReader { */ public $file; + /** + * Selected columns + * @var array + */ + public $columns = array(); + /** * Spreadsheet title * @var [type] @@ -236,6 +242,17 @@ public function limit($amount) return $this->take($amount); } + /** + * Select certain columns + * @param array $columns [description] + * @return [type] [description] + */ + public function select($columns = array()) + { + $this->columns = array_merge($this->columns, $columns); + return $this; + } + /** * Return all sheets/rows * @return [type] [description] @@ -246,7 +263,7 @@ public function all() } /** - * Get first row only + * Get first row/sheet only * @return [type] [description] */ public function first() @@ -567,6 +584,10 @@ protected function _setFormat() */ protected function _parseFile($columns = array()) { + // Merge the selected columns + $columns = array_merge($this->columns, $columns); + + // Parse the file $parser = new ExcelParser($this); $this->parsed = $parser->parseFile($columns); } From 84ca15538d55064db19f73cda3af69412e9b692a Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 14 May 2014 18:04:49 +0000 Subject: [PATCH 0058/1332] Bugfix --- src/Maatwebsite/Excel/Excel.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 4b0b7e38d..75b1edcc2 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -102,7 +102,7 @@ public function load($file, $callback = false) // Do the callback if($callback instanceof Closure) - call_user_func($callback, $this->reader; + call_user_func($callback, $this->reader); // Return the reader object return $this->reader; From b51097cfeb0df61e3d98bb12c68f56a7c1f96aed Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 14 May 2014 19:34:49 +0000 Subject: [PATCH 0059/1332] Couple of fixes + set default cache to in memory --- src/Maatwebsite/Excel/Readers/LaravelExcelReader.php | 9 +++++---- src/config/cache.php | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index c04c33660..e28f0d091 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -257,18 +257,18 @@ public function select($columns = array()) * Return all sheets/rows * @return [type] [description] */ - public function all() + public function all($columns = array()) { - return $this->get(); + return $this->get($columns); } /** * Get first row/sheet only * @return [type] [description] */ - public function first() + public function first($columns = array()) { - return $this->take(1)->get()->first(); + return $this->take(1)->get($columns)->first(); } /** @@ -468,6 +468,7 @@ public function setSeperator($seperator) /** * Set the delimiter + * Calling this after the ->load() will have no effect */ public function setDelimiter($delimiter) { diff --git a/src/config/cache.php b/src/config/cache.php index f55daa1c2..178cdddd8 100644 --- a/src/config/cache.php +++ b/src/config/cache.php @@ -20,7 +20,7 @@ | memory|gzip|serialized|igbinary|discISAM|apc|memcache|temp|wincache|sqlite|sqlite3 | */ - 'driver' => 'discISAM', + 'driver' => 'memory', /* |-------------------------------------------------------------------------- From 065279819d91326f167a88a85181e31cff6b6d93 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 14 May 2014 19:47:53 +0000 Subject: [PATCH 0060/1332] Import docs + start of blade to excel docs --- docs/blade.md | 2 + docs/blade/load-view.md | 29 +++++++++++++ docs/import.md | 9 +++- docs/import/basics.md | 2 + docs/import/cache.md | 12 ++++++ docs/import/calculation.md | 11 +++++ docs/import/config.md | 15 +++++++ docs/import/dates.md | 45 ++++++++++++++++++++ docs/import/extra.md | 34 +++++++++++++++ docs/import/results.md | 84 ++++++++++++++++++++++++++++++++++++++ docs/import/select.md | 23 +++++++++++ 11 files changed, 265 insertions(+), 1 deletion(-) create mode 100644 docs/blade.md create mode 100644 docs/blade/load-view.md create mode 100644 docs/import/cache.md create mode 100644 docs/import/calculation.md create mode 100644 docs/import/config.md create mode 100644 docs/import/dates.md create mode 100644 docs/import/extra.md create mode 100644 docs/import/results.md create mode 100644 docs/import/select.md diff --git a/docs/blade.md b/docs/blade.md new file mode 100644 index 000000000..22d4554f7 --- /dev/null +++ b/docs/blade.md @@ -0,0 +1,2 @@ +@include:Loading a view|load-view +@include:Passing variables|vars \ No newline at end of file diff --git a/docs/blade/load-view.md b/docs/blade/load-view.md new file mode 100644 index 000000000..73f655201 --- /dev/null +++ b/docs/blade/load-view.md @@ -0,0 +1,29 @@ +# @Blade to Excel + +We can utilise the magic of Laravel's Blade engine to power our Excel export. Sharing a view, loading a view per sheet, creating a html table inside a view, basic CSS styling, ... + +# Loading a view for a single sheet + +We can load a view for every sheet we create with `->loadView()`. + + Excel::create('New file', function($excel) { + + $excel->sheet('New sheet', function($sheet) { + + $sheet->loadView('folder.view'); + + }); + + }); + +# Sharing a view for all sheets + +We can share a view for all sheets with `shareView()` + + Excel::shareView('folder.view')->create(); + +# Unsetting a view for a sheet + +When we are using a the share view, but we don't want to use a view for the current sheet, we can use `->unsetView()` + + $sheet->unsetView(); \ No newline at end of file diff --git a/docs/import.md b/docs/import.md index 5f33133bd..5e0a6fb38 100644 --- a/docs/import.md +++ b/docs/import.md @@ -1,2 +1,9 @@ @include:Importing a file|basics -@include:Batch import|batch \ No newline at end of file +@include:Handling results|results +@include:Selecting sheets and columns|select +@include:Dates|dates +@include:Calculation|calculation +@include:Caching and cell caching|cache +@include:Batch import|batch +@include:Import by config|config +@include:Extra|extra \ No newline at end of file diff --git a/docs/import/basics.md b/docs/import/basics.md index 4e1b17a85..f6ad25fbe 100644 --- a/docs/import/basics.md +++ b/docs/import/basics.md @@ -1,5 +1,7 @@ # Importing a file +To start importing a file, you will have to `->load($filename)` it. The callback is optional. + Excel::load('file.xls', function($reader) { // reader methods diff --git a/docs/import/cache.md b/docs/import/cache.md new file mode 100644 index 000000000..56543c56f --- /dev/null +++ b/docs/import/cache.md @@ -0,0 +1,12 @@ +# Caching and Cell caching + +### Cell caching + +You can enable cell caching inside the config `cache.php`. You can choose between a couple of drivers and change a couple of settings. By default the caching is **enabled** and will use **in memory** caching. + +### Remembering results + +If you want to remember the results you can use `->remember($minutes)`. Next time you will load the same file (if still inside the cache time), it will return the cached results. + + // Remember for 10 minutes + $results = $reader->remember(10)->get(); \ No newline at end of file diff --git a/docs/import/calculation.md b/docs/import/calculation.md new file mode 100644 index 000000000..72cfbcecb --- /dev/null +++ b/docs/import/calculation.md @@ -0,0 +1,11 @@ +# Calculate formulas + +By default formulas inside the file are being calculated an a result will be returned. Inside `import.php` config you can change the default behaviour. + +If you want to enable/disable it per import, you can use `->calculate($boolean)` + + // Enable calculation + $reader->calculate(); + + // Disable calculation + $reader->calculate(false); \ No newline at end of file diff --git a/docs/import/config.md b/docs/import/config.md new file mode 100644 index 000000000..3eb55d79d --- /dev/null +++ b/docs/import/config.md @@ -0,0 +1,15 @@ +# Import by Config + +When using advanced Excel files (e.g. without any heading columns), it can be complicated to import those. +`->byConfig()` will help you handle with this problem. + +Inside `excel::import.sheets` config you can find an example. + + Excel::load('file.xls')->byConfig('excel::import.sheets', function($sheet) { + + // The firstname getter will correspond with a cell coordinate set inside the config + $firstname = $sheet->firstname; + + }); + +> **Note:** if you are using multiple sheets. `->byConfig` will loop through all sheets. If these getters are only exist on one sheet, you can always use `->selectSheets()`. \ No newline at end of file diff --git a/docs/import/dates.md b/docs/import/dates.md new file mode 100644 index 000000000..dfebe1ca0 --- /dev/null +++ b/docs/import/dates.md @@ -0,0 +1,45 @@ +# Dates + +By default the dates will be parsed as a **Carbon object**. You can disable date formatting completly insides `import.php` inside `dates.enabled`. + +To enable/disable date formatting per import, use `->formatDates($booleaan, $format)` + + // Format the dates + $reader->formatDates(true); + + // Disable date formatting + $reader->formatDates(false); + + // Format dates + set date format + $reader->formatDates(true, 'Y-m-d'); + +### Format dates + +By default the dates are **not formatted**, but a Carbon object. There are a couple of options to format them. + +#### Formatting results after ->get() + +Inside your loop you can utilise the Carbon method `->format($dateFormat)` + + $rows->each(function($row) { + + $created_at = $row->created_at->format('Y-m-d'); + + }); + +#### Setting a default date format + +Inside the config you can set a default date format. A Carbon object will no longer be returned. + +Or you can use `->setDateFormat()` + + $reader->setDateFormat('Y-m-d'); + +### Setting custom date columns + +Cells which are not Excel formatted dates will not be parsed as a date. To force this behaviour (or to use this with CSV imports), you can set these date columns manually: `->setDateColumns()` + + $reader->setDateColumns(array( + 'created_at', + 'deleted_at' + ))->get(); \ No newline at end of file diff --git a/docs/import/extra.md b/docs/import/extra.md new file mode 100644 index 000000000..df78ed6be --- /dev/null +++ b/docs/import/extra.md @@ -0,0 +1,34 @@ +# Extra + +### Disable using first row as collection attributes + +By default we will use the first row of a file as table heading (so as attribute names for the collection). +You can change the default behaviour inside `import.php` with `import.heading`. + +To disable this per import, use `->noHeading()` + + $reader->noHeading(); + +### Setting the cell name seperator +By default collection attribute names will be set through the first row columns. Spaces will be translated to _ + +**E.g. Created at -> created_at** + +The default behaviour can be changed inside `import.php` config with `'seperator'`. Or you can use `->setSeperator($seperator)` + + $reader->setSeperator('-'); + +### Ignoring empty cells +By default empty cells will not be ignored and presents ass null inside the cell collection. + +To change the default behaviour, you can change `'ignoreEmpty`' inside `import.php` or use `->ignoreEmpty()` + + $reader->ignoreEmpty(); + +### Input encoding + +Inside the `import.php` config you can change the input encoding. In most cases **UTF-8** will be the best solution. Hower if you dump your results. Make sure this the HTML has this exact same meta charset! + +### CSV Settings + +Inside the `csv.php` config you can change the default settings, like the **delimiter, the enclosure and the line endings**. \ No newline at end of file diff --git a/docs/import/results.md b/docs/import/results.md new file mode 100644 index 000000000..7cbeccb9a --- /dev/null +++ b/docs/import/results.md @@ -0,0 +1,84 @@ +# Handling imported results + +### Getting als sheets and rows + +After you have loaded a file, you can `->get()` the results: + + Excel::load('file.xls', function($reader) { + + })->get(); + +or + + Excel::load('file.xls', function($reader) { + + // Getting all results + $results = $reader->get(); + + // ->all() is a wrapper for ->get() and will work the same + $results = $reader->all(); + + }); + +> The `->get()` and `->all()` method will return a sheet- or row collection, depending on the amount of sheets the file has. You can disable this feature inside `import.php` config by settings `'force_sheets_collection'` to `true`. When set to true it will always return a sheet collection. + +### Collections + +Sheets, rows and cells are collections, this means after doing a `->get()` you can use all default collection methods. + + // E.g. group the results + $reader->get()->groupBy('firstname'); + +### Getting the first sheet or row + +To get the first sheet or row, you can utilise `->first()`. + + $reader->first(); + +> **Note:** depending on the config `'force_sheets_collection'` it will return the first row or sheet. + +### Limiting the results + +When you only want to return the first x rows of a sheet, you can use `->take()` or `->limit()`. + + // You can either use ->take() + $reader->take(10); + + // Or ->limit() + $reader->limit(10); + +### Result mutators + +When you want to get an array instead of an object, you can use `->toArray()`. + + $reader->toArray(); + +When you want an object, you can alternativly (instead of get() or all()) use `->toObject()` + + $reader->toObject(); + +### Displaying results + +You can dump the results to a readable output by using `->dump()` or `->dd()` + + // Dump the results + $reader->dump(); + + // Dump results and die + $reader->dd(); + +### Iterating the results + +You can iterate the results by using `->each()` + + // Loop through all sheets + $reader->each(function($sheet) { + + // Loop through all rows + $sheet->each(function($row) { + + }); + + }); + +> A simple foreach will work as well of course \ No newline at end of file diff --git a/docs/import/select.md b/docs/import/select.md new file mode 100644 index 000000000..caf9ecd7b --- /dev/null +++ b/docs/import/select.md @@ -0,0 +1,23 @@ +# Selecting sheets and columns + +### Selecting one specific sheet +If you want to select a single sheet, you can use `->selectSheets($name)`. Only that sheet will be loaded. + + Excel::selectSheets('sheet1')->load(); + +### Selecting multiple sheets +If you want to select multiple sheets inside your file, you can pass an array as parameter; + + Excel::selectSheets(array('sheet1', 'sheet2'))->load(); + +### Selecting columns + +If you want to select only a couple of columns, you can use `->select($columns)` or pass an array as first parameter of `->get($columns)` + + // Select + $reader->select(array('firstname', 'lastname'))->get(); + + // Or + $reader->get(array('firstname', 'lastname')); + +> All get methods (like all(), first(), dump(), toArray(), ...) accept an array of columns \ No newline at end of file From 526eed032ccb80f4928cd9c0a32364f610b49eda Mon Sep 17 00:00:00 2001 From: Patrick Brouwer Date: Thu, 15 May 2014 21:02:07 +0200 Subject: [PATCH 0061/1332] Added more blade docs --- docs/blade/load-view.md | 16 ++++++++++++++++ docs/blade/vars.md | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 docs/blade/vars.md diff --git a/docs/blade/load-view.md b/docs/blade/load-view.md index 73f655201..27df31d83 100644 --- a/docs/blade/load-view.md +++ b/docs/blade/load-view.md @@ -16,6 +16,22 @@ We can load a view for every sheet we create with `->loadView()`. }); +# Using different views for different sheets + + Excel::create('New file', function($excel) { + + $excel->sheet('First sheet', function($sheet) { + + $sheet->loadView('view_first'); + }); + + $excel->sheet('Second sheet', function($sheet) { + + $sheet->loadView('view_second'); + }); + + }); + # Sharing a view for all sheets We can share a view for all sheets with `shareView()` diff --git a/docs/blade/vars.md b/docs/blade/vars.md new file mode 100644 index 000000000..6c1b45f40 --- /dev/null +++ b/docs/blade/vars.md @@ -0,0 +1,19 @@ +# Passing variables to the view + +### As parameter + +We can pass variable to the view by using the second parameter inside the `loadView()` method. + + $sheet->loadView('view', array('key' => 'value')); + +### With with() + +Alternativly you can use the `with()` method which works the same as with Laravel views. + + // Using normal with() + $sheet->loadView('view') + ->with('key', 'value'); + + // using dynamic with() + $sheet->loadView('view') + ->withKey('value'); \ No newline at end of file From e7bd92297dd0c5d05f0784cb0e6f3b694b0a5a66 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 07:54:52 +0200 Subject: [PATCH 0062/1332] Update config.md Typos --- docs/getting-started/config.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/getting-started/config.md b/docs/getting-started/config.md index 6686ae190..9656be557 100644 --- a/docs/getting-started/config.md +++ b/docs/getting-started/config.md @@ -1,8 +1,8 @@ #Config -Laravel Excel includes several config settings for import-, export-, view-, CSV-specific settings, +Laravel Excel includes several config settings for import-, export-, view- and CSV-specific settings. Use the artisan publish command to publish the config file to your project. php artisan config:publish maatwebsite/excel -The config files can now be found at `app/config/packages/maatwebsite/excel` \ No newline at end of file +The config files can now be found at `app/config/packages/maatwebsite/excel` From db7663edc07f380dd46a647ae96fd92980bb5548 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 08:01:39 +0200 Subject: [PATCH 0063/1332] Update contributing.md Typos --- docs/getting-started/contributing.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/getting-started/contributing.md b/docs/getting-started/contributing.md index f01c3c8b3..9c934dbfd 100644 --- a/docs/getting-started/contributing.md +++ b/docs/getting-started/contributing.md @@ -2,11 +2,11 @@ ### Bug fixes -**ALL** bug fixes should be made to the `dev-develop` branch which they belong. Bug fixes should never be sent to the `master` branch. +**ALL** bug fixes should be made to the `dev-develop` branch where they belong. Bug fixes should never be sent to the `master` branch. ### Pull Requests -Every pull request should pass the unit tests. If you include new functionality, make sure you include a test. Pull request will be evaluated and possibly added to the next stable release. +Every pull request should pass the unit tests. If you include new functionality, make sure you include a test. Pull requests will be evaluated and possibly added to the next stable release. ### Feature Requests @@ -14,9 +14,9 @@ If you have an idea for a new feature you would like to see added to Laravel Exc ### Coding Guidelines -Laravel follows the [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) and [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md) coding standards. In addition to these standards, below is a list of other coding standards that should be followed: +Laravel, and therefore Maatwebsite's Laravel Excel follows the [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) and [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md) coding standards. In addition to these standards, below is a list of other coding standards that should be followed: - Namespace declarations should be on the same line as ` Date: Fri, 16 May 2014 08:02:54 +0200 Subject: [PATCH 0064/1332] Update license.md Typos --- docs/getting-started/license.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/getting-started/license.md b/docs/getting-started/license.md index 6d69a602c..f0f26a1b9 100644 --- a/docs/getting-started/license.md +++ b/docs/getting-started/license.md @@ -1,3 +1,3 @@ #License -This package is licensed under LGPL. You are free to use it in personal and commercial projects. The code can be forked and modified, but original copyright author should always be included! \ No newline at end of file +This package is licensed under LGPL. You are free to use it in personal and commercial projects. The code can be forked and modified, but the original copyright author should always be included! From f4c77b3ab0cb78b6d589e8d90863a82e84604ce7 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 08:04:32 +0200 Subject: [PATCH 0065/1332] Update basics.md --- docs/import/basics.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/import/basics.md b/docs/import/basics.md index f6ad25fbe..9af696aec 100644 --- a/docs/import/basics.md +++ b/docs/import/basics.md @@ -1,9 +1,9 @@ # Importing a file -To start importing a file, you will have to `->load($filename)` it. The callback is optional. +To start importing a file, you can use `->load($filename)`. The callback is optional. Excel::load('file.xls', function($reader) { // reader methods - }); \ No newline at end of file + }); From 24622942a57700bb2a21a0afacb9fecce8a104d6 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 08:11:50 +0200 Subject: [PATCH 0066/1332] Update results.md Typos and edits | FP --- docs/import/results.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/import/results.md b/docs/import/results.md index 7cbeccb9a..8538fd836 100644 --- a/docs/import/results.md +++ b/docs/import/results.md @@ -1,8 +1,8 @@ # Handling imported results -### Getting als sheets and rows +### Getting all sheets and rows -After you have loaded a file, you can `->get()` the results: +After you have loaded a file, you can `->get()` the results like so: Excel::load('file.xls', function($reader) { @@ -20,7 +20,7 @@ or }); -> The `->get()` and `->all()` method will return a sheet- or row collection, depending on the amount of sheets the file has. You can disable this feature inside `import.php` config by settings `'force_sheets_collection'` to `true`. When set to true it will always return a sheet collection. +> The `->get()` and `->all()` methods will return a sheet or row collection, depending on the amount of sheets the file has. You can disable this feature inside the `import.php` config by setting `'force_sheets_collection'` to `true`. When set to true it will always return a sheet collection. ### Collections @@ -53,13 +53,13 @@ When you want to get an array instead of an object, you can use `->toArray()`. $reader->toArray(); -When you want an object, you can alternativly (instead of get() or all()) use `->toObject()` +When you want an object, you can alternativly (instead of get() or all()) use `->toObject()`. $reader->toObject(); ### Displaying results -You can dump the results to a readable output by using `->dump()` or `->dd()` +You can dump the results to a readable output by using `->dump()` or `->dd()`. // Dump the results $reader->dump(); @@ -69,7 +69,7 @@ You can dump the results to a readable output by using `->dump()` or `->dd()` ### Iterating the results -You can iterate the results by using `->each()` +You can iterate the results by using `->each()`. // Loop through all sheets $reader->each(function($sheet) { @@ -81,4 +81,4 @@ You can iterate the results by using `->each()` }); -> A simple foreach will work as well of course \ No newline at end of file +> Alternatively you can also `foreach` the results. From fac5f6373d120784a69398bb9f14f5b81a74adb1 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 08:13:44 +0200 Subject: [PATCH 0067/1332] Update select.md Typos and edits | FP --- docs/import/select.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/import/select.md b/docs/import/select.md index caf9ecd7b..cce3bd5dc 100644 --- a/docs/import/select.md +++ b/docs/import/select.md @@ -6,13 +6,13 @@ If you want to select a single sheet, you can use `->selectSheets($name)`. Only Excel::selectSheets('sheet1')->load(); ### Selecting multiple sheets -If you want to select multiple sheets inside your file, you can pass an array as parameter; +If you want to select multiple sheets inside your file, you can pass an array as the parameter; Excel::selectSheets(array('sheet1', 'sheet2'))->load(); ### Selecting columns -If you want to select only a couple of columns, you can use `->select($columns)` or pass an array as first parameter of `->get($columns)` +If you want to select only a couple of columns, you can use `->select($columns)` or pass an array as the first parameter of `->get($columns)`. // Select $reader->select(array('firstname', 'lastname'))->get(); @@ -20,4 +20,4 @@ If you want to select only a couple of columns, you can use `->select($columns)` // Or $reader->get(array('firstname', 'lastname')); -> All get methods (like all(), first(), dump(), toArray(), ...) accept an array of columns \ No newline at end of file +> All get methods (like all(), first(), dump(), toArray(), ...) accept an array of columns. From 52a53b9f51bcb3bb0af733344f1c957c578ab15f Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 08:21:31 +0200 Subject: [PATCH 0068/1332] Update dates.md Typos and edits | FP --- docs/import/dates.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/import/dates.md b/docs/import/dates.md index dfebe1ca0..8d1eba346 100644 --- a/docs/import/dates.md +++ b/docs/import/dates.md @@ -1,8 +1,8 @@ # Dates -By default the dates will be parsed as a **Carbon object**. You can disable date formatting completly insides `import.php` inside `dates.enabled`. +By default the dates will be parsed as a **[Carbon object](https://github.com/briannesbitt/Carbon)**. You can disable date formatting completly inside `import.php` by setting `dates.enabled` to `false`. -To enable/disable date formatting per import, use `->formatDates($booleaan, $format)` +To enable/disable date formatting for a single import, use `->formatDates($boolean, $format)` // Format the dates $reader->formatDates(true); @@ -15,7 +15,7 @@ To enable/disable date formatting per import, use `->formatDates($booleaan, $for ### Format dates -By default the dates are **not formatted**, but a Carbon object. There are a couple of options to format them. +By default the dates are **not formatted**, but returned as a Carbon object. There are a couple of options to format them. #### Formatting results after ->get() @@ -42,4 +42,4 @@ Cells which are not Excel formatted dates will not be parsed as a date. To force $reader->setDateColumns(array( 'created_at', 'deleted_at' - ))->get(); \ No newline at end of file + ))->get(); From 07fb4d1ad954cb7ef65f489e9b746eb5929571f7 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 08:25:22 +0200 Subject: [PATCH 0069/1332] Update calculation.md Typos and edits | FP --- docs/import/calculation.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/import/calculation.md b/docs/import/calculation.md index 72cfbcecb..22ea7062f 100644 --- a/docs/import/calculation.md +++ b/docs/import/calculation.md @@ -1,11 +1,11 @@ # Calculate formulas -By default formulas inside the file are being calculated an a result will be returned. Inside `import.php` config you can change the default behaviour. +By default formulas inside the file are being calculated and it's result will be returned. Inside `import.php` config you can change the default behaviour by setting `calculate` to the desired preference. -If you want to enable/disable it per import, you can use `->calculate($boolean)` +If you want to enable/disable it for a single import, you can use `->calculate($boolean)` // Enable calculation $reader->calculate(); // Disable calculation - $reader->calculate(false); \ No newline at end of file + $reader->calculate(false); From 683dc884a108aeae69eb558328355efbdbd8271f Mon Sep 17 00:00:00 2001 From: Frank Peters Date: Fri, 16 May 2014 08:37:06 +0200 Subject: [PATCH 0070/1332] * Typos and edits to import docs --- docs/import/batch.md | 2 +- docs/import/cache.md | 2 +- docs/import/config.md | 4 ++-- docs/import/extra.md | 14 +++++++------- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/import/batch.md b/docs/import/batch.md index 8089efb7a..4e3258f41 100644 --- a/docs/import/batch.md +++ b/docs/import/batch.md @@ -2,7 +2,7 @@ ### Import a folder -To import an entire folder (only xls, xlsx and csv files will be used), set the folder as first parameter. +To import an entire folder (only xls, xlsx and csv files will be imported), set the folder as the first parameter. Excel::batch('app/storage/uploads', function($rows, $file) { diff --git a/docs/import/cache.md b/docs/import/cache.md index 56543c56f..621ab64cb 100644 --- a/docs/import/cache.md +++ b/docs/import/cache.md @@ -6,7 +6,7 @@ You can enable cell caching inside the config `cache.php`. You can choose betwee ### Remembering results -If you want to remember the results you can use `->remember($minutes)`. Next time you will load the same file (if still inside the cache time), it will return the cached results. +If you want to remember the results you can use `->remember($minutes)`. Next time you will load the same file (if it's still inside the cache), it will return the cached results. // Remember for 10 minutes $results = $reader->remember(10)->get(); \ No newline at end of file diff --git a/docs/import/config.md b/docs/import/config.md index 3eb55d79d..3a92cfef3 100644 --- a/docs/import/config.md +++ b/docs/import/config.md @@ -1,7 +1,7 @@ # Import by Config -When using advanced Excel files (e.g. without any heading columns), it can be complicated to import those. -`->byConfig()` will help you handle with this problem. +When using advanced Excel files (e.g. without any heading columns), it can be complicated to import these. +`->byConfig()` will help you handle this problem. Inside `excel::import.sheets` config you can find an example. diff --git a/docs/import/extra.md b/docs/import/extra.md index df78ed6be..28c2da930 100644 --- a/docs/import/extra.md +++ b/docs/import/extra.md @@ -5,30 +5,30 @@ By default we will use the first row of a file as table heading (so as attribute names for the collection). You can change the default behaviour inside `import.php` with `import.heading`. -To disable this per import, use `->noHeading()` +To disable this for a single import, use `->noHeading()`. $reader->noHeading(); ### Setting the cell name seperator -By default collection attribute names will be set through the first row columns. Spaces will be translated to _ +By default collection attribute names will be set by looking at the first row columns. Spaces will be translated to `_`. **E.g. Created at -> created_at** -The default behaviour can be changed inside `import.php` config with `'seperator'`. Or you can use `->setSeperator($seperator)` +The default behaviour can be changed inside the `import.php` config by changing `'seperator'`. Or you can use `->setSeperator($seperator)`. $reader->setSeperator('-'); ### Ignoring empty cells -By default empty cells will not be ignored and presents ass null inside the cell collection. +By default empty cells will not be ignored and presented as null inside the cell collection. -To change the default behaviour, you can change `'ignoreEmpty`' inside `import.php` or use `->ignoreEmpty()` +To change the default behaviour, you can change `'ignoreEmpty`' inside `import.php` or use `->ignoreEmpty()`. $reader->ignoreEmpty(); ### Input encoding -Inside the `import.php` config you can change the input encoding. In most cases **UTF-8** will be the best solution. Hower if you dump your results. Make sure this the HTML has this exact same meta charset! +Inside the `import.php` config you can change the input encoding. In most cases **UTF-8** will be the best solution. Hower if you dump your results make sure your HTML page has this exact same meta charset! ### CSV Settings -Inside the `csv.php` config you can change the default settings, like the **delimiter, the enclosure and the line endings**. \ No newline at end of file +Inside the `csv.php` config you can change the default settings, like the `delimiter`, the `enclosure` and the `line_ending`. \ No newline at end of file From 2aeb8c22b0b372a0e32b14e4088f16db23409570 Mon Sep 17 00:00:00 2001 From: Frank Peters Date: Fri, 16 May 2014 08:51:28 +0200 Subject: [PATCH 0071/1332] * Typos and edits to export docs --- docs/export/array.md | 4 ++-- docs/export/autofilter.md | 4 ++-- docs/export/autosize.md | 8 ++++---- docs/export/call.md | 2 +- docs/export/export.md | 2 +- docs/export/merge.md | 4 ++-- docs/export/sheet-styling.md | 2 +- docs/export/sheets.md | 6 +++--- docs/export/simple.md | 8 ++++---- docs/export/sizing.md | 12 ++++++------ docs/export/store.md | 8 ++++---- 11 files changed, 30 insertions(+), 30 deletions(-) diff --git a/docs/export/array.md b/docs/export/array.md index 97562bcc8..c6c835a99 100644 --- a/docs/export/array.md +++ b/docs/export/array.md @@ -1,6 +1,6 @@ # Creating a sheet from an array -To create a new file from an array use `->fromArray()` inside the sheet closure: +To create a new file from an array use `->fromArray()` inside the sheet closure. Excel::create('Filename', function($excel) { @@ -15,7 +15,7 @@ To create a new file from an array use `->fromArray()` inside the sheet closure: })->export('xls'); -Alternativly you can use `->with()` +Alternatively you can use `->with()`. $sheet->with(array( array('data1', 'data2'), diff --git a/docs/export/autofilter.md b/docs/export/autofilter.md index 00fbd818c..d6624f3c2 100644 --- a/docs/export/autofilter.md +++ b/docs/export/autofilter.md @@ -1,8 +1,8 @@ # Auto filter -To enable the auto filter use `->setAutoFilter($range = false)` +To enable the auto filter use `->setAutoFilter($range = false)`. - // Autofilter for entire sheet + // Auto filter for entire sheet $sheet->setAutoFilter(); // Set auto filter for a range diff --git a/docs/export/autosize.md b/docs/export/autosize.md index 5fac6769f..66cc9bb83 100644 --- a/docs/export/autosize.md +++ b/docs/export/autosize.md @@ -2,15 +2,15 @@ By default the exported file be automatically auto sized. To change this behaviour you can either change the config or use the setters: - // Set autosize for sheet + // Set auto size for sheet $sheet->setAutoSize(true); - // Disable autosize for sheet + // Disable auto size for sheet $sheet->setAutoSize(false); - // Disable autosize for columns + // Disable auto size for columns $sheet->setAutoSize(array( 'A', 'C' )); -> The default config setting can be found in: `export.php` \ No newline at end of file +> The default config setting can be found in: `export.php`. \ No newline at end of file diff --git a/docs/export/call.md b/docs/export/call.md index 3c2626d87..8a1d5590e 100644 --- a/docs/export/call.md +++ b/docs/export/call.md @@ -1,4 +1,4 @@ -# Calling PHPExcel native methods +# Calling PHPExcel's native methods It's possible to call all native PHPExcel methods on the `$excel` and `$sheet` objects. diff --git a/docs/export/export.md b/docs/export/export.md index c164ae9ae..b5c744f7d 100644 --- a/docs/export/export.md +++ b/docs/export/export.md @@ -1,6 +1,6 @@ # Exporting -To download the created file, use `->export($ext)` or `->download($ext)` +To download the created file, use `->export($ext)` or `->download($ext)`. #### Export to Excel5 (xls) diff --git a/docs/export/merge.md b/docs/export/merge.md index 70a2d4d6f..0eb0e48fd 100644 --- a/docs/export/merge.md +++ b/docs/export/merge.md @@ -2,13 +2,13 @@ ### Merging cells -To merge a range of cells, use `->mergeCells($range)` +To merge a range of cells, use `->mergeCells($range)`. $sheet->mergeCells('A1:E1'); ### Merging columns and rows -To merge columns and rows, use `->setMergeColumn($array)` +To merge columns and rows, use `->setMergeColumn($array)`. $sheet->setMergeColumn(array( 'columns' => array('A','B','C','D'), diff --git a/docs/export/sheet-styling.md b/docs/export/sheet-styling.md index fc3147056..9fa86c823 100644 --- a/docs/export/sheet-styling.md +++ b/docs/export/sheet-styling.md @@ -10,7 +10,7 @@ To change the font for the current sheet use `->setFont($array)`: 'bold' => true )); -#### Seperate setters +#### Separate setters // Font family $sheet->setFontFamily('Comic Sans MS'); diff --git a/docs/export/sheets.md b/docs/export/sheets.md index 07bf8a123..0912bedcd 100644 --- a/docs/export/sheets.md +++ b/docs/export/sheets.md @@ -2,13 +2,13 @@ ### Creating a sheet -To create a new sheet inside our newly created file, use `->sheets('Sheetname')`: +To create a new sheet inside our newly created file, use `->sheets('Sheetname')`. Excel::create('Filename', function($excel) { $excel->sheet('Sheetname', function($sheet) { - // sheet manipulation + // Sheet manipulation }); @@ -35,7 +35,7 @@ You can set as many sheets as you like inside the file: ### Changing properties -There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See `app/config/packages/maatwebsite/excel/config.php` +There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See `app/config/packages/maatwebsite/excel/config.php`. Excel::create('Filename', function($excel) { diff --git a/docs/export/simple.md b/docs/export/simple.md index ef2c263f5..f9704d870 100644 --- a/docs/export/simple.md +++ b/docs/export/simple.md @@ -2,7 +2,7 @@ ### Basics -A new file can be created using the `create` method with the filename as first paramater. +A new file can be created using the `create` method with the filename as first parameter. Excel::create('Filename'); @@ -10,13 +10,13 @@ To manipulate the creation of the file you can use the callback Excel::create('Filename', function($excel) { - // call writer methods here + // Call writer methods here }); ### Changing properties -There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See `app/config/packages/maatwebsite/excel/config.php` +There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See `app/config/packages/maatwebsite/excel/config.php`. Excel::create('Filename', function($excel) { @@ -27,7 +27,7 @@ There are a couple of properties we can change inside the closure. Most of them $excel->setCreator('Maatwebsite') ->setCompany('Maatwebsite'); - // Call them seperatly + // Call them separately $excel->setDescription('A demonstration to change the file properties'); }); diff --git a/docs/export/sizing.md b/docs/export/sizing.md index 3b4437a15..824e095a9 100644 --- a/docs/export/sizing.md +++ b/docs/export/sizing.md @@ -2,9 +2,9 @@ ### Set column width -To set the column width use `->setWidth($cell, $width)` +To set the column width use `->setWidth($cell, $width)`. - // Set width for single column + // Set width for a single column $sheet->setWidth('A', 5); // Set width for multiple cells @@ -15,9 +15,9 @@ To set the column width use `->setWidth($cell, $width)` ### Set row height -To set the row height use `->setHeight($row, $height)` +To set the row height use `->setHeight($row, $height)`. - // Set height for single row + // Set height for a single row $sheet->setHeight(1, 50); // Set height for multiple rows @@ -28,9 +28,9 @@ To set the row height use `->setHeight($row, $height)` ### Set cell size -To set the cell size use `->setSize($cell, $width, $height)` +To set the cell size use `->setSize($cell, $width, $height)`. - // Set size for single cell + // Set size for a single cell $sheet->setSize('A1', 500, 50); $sheet->setSize(array( diff --git a/docs/export/store.md b/docs/export/store.md index b50490c35..823e304b5 100644 --- a/docs/export/store.md +++ b/docs/export/store.md @@ -1,6 +1,6 @@ -# Store to server +# Store on server -To store the created file to the server, use `->store($ext, $path = false, $returnInfo = false)` or `->save()` +To store the created file on the server, use `->store($ext, $path = false, $returnInfo = false)` or `->save()`. ### Normal export to default storage path @@ -14,7 +14,7 @@ By default the file will be stored inside the `app/storage/exports` folder, whic ### Normal export to custom storage path -If you want to use a custom storage path (e.g. to seperate the files per client), you can set the folder as the second parameter. +If you want to use a custom storage path (e.g. to separate the files per client), you can set the folder as the second parameter. ->store('xls', storage_path('excel/exports')); @@ -24,7 +24,7 @@ If you want to use a custom storage path (e.g. to seperate the files per client) ### Store and return storage info -If you want to return storage information, set the third paramter to true or change the config setting inside `export.php` +If you want to return storage information, set the third paramter to true or change the config setting inside `export.php`. ->store('xls', false, true); From 387c9374e00cb153c968de60f96b6c8bb0f84000 Mon Sep 17 00:00:00 2001 From: Frank Peters Date: Fri, 16 May 2014 09:04:47 +0200 Subject: [PATCH 0072/1332] * Typos and edits in blade docs --- docs/blade/load-view.md | 4 ++-- docs/blade/vars.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/blade/load-view.md b/docs/blade/load-view.md index 27df31d83..697e8747b 100644 --- a/docs/blade/load-view.md +++ b/docs/blade/load-view.md @@ -34,12 +34,12 @@ We can load a view for every sheet we create with `->loadView()`. # Sharing a view for all sheets -We can share a view for all sheets with `shareView()` +We can share a view for all sheets with `shareView()`. Excel::shareView('folder.view')->create(); # Unsetting a view for a sheet -When we are using a the share view, but we don't want to use a view for the current sheet, we can use `->unsetView()` +When we are using a shared view, but we don't want to use a view for the current sheet, we can use `->unsetView()`. $sheet->unsetView(); \ No newline at end of file diff --git a/docs/blade/vars.md b/docs/blade/vars.md index 6c1b45f40..ed5400121 100644 --- a/docs/blade/vars.md +++ b/docs/blade/vars.md @@ -2,13 +2,13 @@ ### As parameter -We can pass variable to the view by using the second parameter inside the `loadView()` method. +We can pass variables to the view by using the second parameter inside the `loadView()` method. $sheet->loadView('view', array('key' => 'value')); ### With with() -Alternativly you can use the `with()` method which works the same as with Laravel views. +Alternatively you can use the `with()` method which works the same as with Laravel views. // Using normal with() $sheet->loadView('view') From 61eeb70403df8eb5e5f9243e2a3b8c9697bf29be Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 18:55:19 +0200 Subject: [PATCH 0073/1332] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 031e9fe71..8b8a2d244 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ [![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) [![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) +> Laravel Excel **1.0.0** is coming this weekend! + #New to v0.3.x - Possibility to call **all native PHPExcel methods** - seperator config value for label formatting (default is `-`) From 0af1b07b39582c80e031e766e648706df9562c59 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 18:59:18 +0200 Subject: [PATCH 0074/1332] Update README.md --- README.md | 308 +----------------------------------------------------- 1 file changed, 1 insertion(+), 307 deletions(-) diff --git a/README.md b/README.md index 624d44801..2fb981605 100644 --- a/README.md +++ b/README.md @@ -4,311 +4,5 @@ [![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) [![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) [![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) -#New to v0.3.x -- Possibility to call **all native PHPExcel methods** -- seperator config value for label formatting (default is `-`) -- loadView supports `->withKey('value')` & `->with('key', 'value')` to set view data -- Multiple sheets with support for a different view per sheet (or share the view) -- CSV import fix -- Date formatting fix -- `loadView()` inline styles parsing (including style, rowspan, colspan, align, valign) -- `store()` can return information about the storage or can be followed by `->export()` -#Installation - -Require this package in your `composer.json` and update composer. This will download the package and PHPExcel of PHPOffice. -```php -"maatwebsite/excel": "dev-master" -``` - -After updating composer, add the ServiceProvider to the providers array in `app/config/app.php` -```php -'Maatwebsite\Excel\ExcelServiceProvider', -``` - -You can use the facade for shorter code. Add this to your aliasses: -```php -'Excel' => 'Maatwebsite\Excel\Facades\Excel', -``` - -#Exporting - -For creating an Excel file use: -```php -Excel::create('ExcelName') - ->sheet('SheetName') - ->with(array( - array('data1', 'data2'), - array('data3', 'data4') - )) - ->export('xls'); -``` - -Multiple sheets are allowed -```php -Excel::create('ExcelName') - ->sheet('SheetName') - ->with(array('data', 'data')) - ->sheet('SheetName') - ->with(array('data', 'data')) - ->export('xls'); -``` - -Export as CSV by using: -```php -->export('csv'); -``` - -Export as Excel2007 by using: -```php -->export('xlsx'); -``` - -#Export from View file - -It's possible to export a blade view file to xls or csv. The view file must be a table. -Use `loadView()` with a view file and data to be used inside the view. -```php -Excel::loadView('folder.file', array('key' => 'value'))->export('xls'); -``` - -Alternatively you can use `with('key', 'value')` or `withKey('value')` as view data setters. -```php -Excel::loadView('folder.file') - ->with('first', 'value1') - ->withSecond('value2') - ->export('xls'); -``` - -If you want to give the file a name chain `setTitle()` after the `loadView()` -```php -Excel::sheet('SheetName')->loadView('folder.file', array('key' => 'value')) - ->setTitle('Title') - ->export('xls'); -``` - -If you want to create multiple cheats and share or use different views for these seperate sheets, you should call the closure -```php -Excel::loadView('excel.reports') - ->sheet('Daily', function($sheet) use($dailyReports) { - - $sheet->withReports($dailyReports); - - })->sheet('Weekly', function($sheet) use($weeklyReports) { - - $sheet->withReports($weeklyReports); - - })->setTitle('Reports')->export('xls'); -``` - -Optionally you can change the view inside the closure. -```php -Excel::sheet('Daily', function($sheet) use($dailyReports) { - - $sheet->loadView('excel.reports.daily'); - $sheet->withReports($dailyReports); - - })->sheet('Weekly', function($sheet) use($weeklyReports) { - - $sheet->loadView('excel.reports.weekly'); - $sheet->withReports($weeklyReports); - - })->setTitle('Reports')->export('xls'); -``` - ->Closures are only accepted when using a view. - -To change the sheet's orientation, use `$sheet->setOrientation('landscape')` - -## View styling - -It possible to use some basic styling inside the table. -HTML tags `, and ` are supported at this moment. - -Table attributes (`align, valign, rowspan & colspan`) will be properly parsed. - -Most of the inline styles are parsed (style="background: #000000"): - -| Style tag name | Value | -| ------------- |:-------------:| -| background | #000000 | -| color | #FFFFFF | -| font-weight | bold | -| font-style | italic | -| font-weight | bold | -| font-size | 20px | -| font-family | Open Sans | -| text-decoration | underline / line-through | -| text-align | center/left/right/justify | -| vertical-align | top/middle/bottom/justify | -| borders | 1px dashed #CCC | -| border-* | 1px dashed #CCC | - -#Store to server - -To store the file to the server use `store($extension, $path)` The path is optional, when this is empty, the default setting in the config will be used. -```php -$file = Excel::loadView('folder.file', array('data')) - ->setTitle('Title') - ->sheet('SheetName') - ->store('xls'); -``` - -The `store($ext, $path, true)` method returns information about the stored file (filename, location, extension, ...); - -When the third parameter is false, it's possible to chain other methods. This example will store and export the same file: -```php -$file = Excel::loadView('folder.file', array('data')) - ->setTitle('Title') - ->sheet('SheetName') - ->store('xls') - ->export('xls'); -``` - -#Freeze / lock rows and columns - -To freeze the first row of the sheet: -```php -->freezeFirstRow() -``` -To freeze the first column of the sheet: -```php -->freezeFirstColumn() -``` - -To freeze the first row and first column of the sheet: -```php -->freezeFirstRowAndColumn() -``` - -Freeze based on coordinate -```php -->setFreeze('B1') -``` - -#Importing - -To import CSV data: -```php -Excel::load('file.csv')->toArray(); -``` - -Optionally you can select columns, by their column index. -An empty `select()`, or no select at all, means we will return all columns -```php -Excel::load('file.csv')->select(array(1, 2))->toArray(); -``` - -If the first row is the table heading, you can give the `load()` method an extra parameter. This will make sure the first row is interpreted as heading. These seperate columns values will be used as array indices. Now you can select columns by their name. Note that the string will be lowercase and spaces will be replaced by `-`. -```php -Excel::load('file.csv', true)->select(array('column1', 'column2'))->toArray(); -``` - -To change the input encoding (default is UTF8), use the third parameter of `load()` -```php -Excel::load('file.csv', false, 'ISO-8859-1')->toArray(); -``` - -The delimiter can be changed right after the file load with `setDelimiter()`. The default delimiter is `,`, which has been set in the config file -```php -Excel::load('file.csv')->setDelimiter(';')->toArray(); -``` - -By default cells with formulas will not be calculated. If you want to calculate them, use the `calculate()` chain. You can change the default inside the config. -```php -Excel::load('file.xls')->calculate()->toArray(); -``` - -By default cells will date/timestamps will be parsed to a PHP date Object and converted to Y-m-d. -You can disable this feature by using `formatDates(false)` -```php -Excel::load('file.xls')->formatDates(false)->toArray(); -``` - -The date format can be changed by using `setDateFormat('Y-m-d')`. You can use all PHP Datetime formats; -```php -Excel::load('file.xls')->setDateFormat('Y-m-d')->toArray(); -``` - -Optionally you can use Carbon to format the date. Use `useCarbon($methodName)` -```php -Excel::load('file.xls')->useCarbon('diffForHumans')->toArray(); -``` - -If you want to limit the data which will be parsed, use `limit()`. -```php -Excel::load('file.csv')->limit(10)->toArray(); -``` - -If you want to output the loaded data to an object, use `toObject()` -```php -Excel::load('file.csv')->toObject(); -``` - -For developping purposes you can choose to dump the returned parsed file to a readable array: -```php -Excel::load('file.csv')->dump(); -``` - -#Converting - -To convert from one filetype to another, use `convert()`: -```php -return Excel::load('file.csv')->convert('xls'); -``` - -#Cell and range formatting - -If you want to format a certain column or range, you can use `setColumnFormat(array())`. -Use the column coordinate or range as array index and use the format code as array value. - -Example to get two leading zeros before the number for one column -```php -->setColumnFormat(array( - 'A' => '0000' - )) -``` - -Example to get two leading zeros before the number with a range: -```php -->setColumnFormat(array( - 'A2:K2' => '0000' - )) -``` - -#Auto filter - -Setting filters on the heading -```php -->setAutoFilter() -``` - -#Setting and styling borders - -To style and set all borders use: -```php -->setAllBorder('thick') -``` - -To style the border of a range -```php -->setBorder('A1:F10','thick') -``` - -You can use all the PHP Excel border styles. - -#Config - -Optional settings can be found in the config file. Use the artisan publish command to publish the config file to your project. -```php -php artisan config:publish maatwebsite/excel -``` - -#v1.0.0 TODO - -* Unit testing -* Cell caching - -#License - -This package is licensed under LGPL. You are free to use it in personal and non-commercial projects. The code can be forked and modified, but original copyright author should always be included! +Documentation at: http://www.maatwebsite.nl/excel/docs From 0af95e926877cbc8b67d4cea451fa57c923c2186 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 18:59:32 +0200 Subject: [PATCH 0075/1332] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2fb981605..eaad0534c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel 4 Wrapper for PHPExcel v0.4.0 - DEV +## Laravel 4 Wrapper for PHPExcel v1.0.0-RC [![Build Status](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel.svg?branch=develop)](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel) [![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) From 22cd3046325fa035ec3883fc9bb4b05886322c69 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 22:36:30 +0200 Subject: [PATCH 0076/1332] Update README.md --- README.md | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index eaad0534c..7b363ff15 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,65 @@ -## Laravel 4 Wrapper for PHPExcel v1.0.0-RC +## Laravel Excel v1.0.0 + +[](http://www.maatwebsite.nl/laravel-excel/docs) [![Build Status](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel.svg?branch=develop)](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel) [![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) [![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) [![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) -Documentation at: http://www.maatwebsite.nl/excel/docs +Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4 with a touch of the Laravel Magic: import files to collections, export views to Excel, ... + +```php + Excel::create('Laravel Excel', function($excel) { + + $excel->sheet('Excel sheet', function($sheet) { + + $sheet->setOrientation('landscape'); + + }); + + })->export('xls'); +``` + +#Installation + +Require this package in your `composer.json` and update composer. This will download the package and PHPExcel of PHPOffice. + +```php + "maatwebsite/excel": "1.*" +``` + +After updating composer, add the ServiceProvider to the providers array in `app/config/app.php` + +```php + 'Maatwebsite\Excel\ExcelServiceProvider', +``` + +You can use the facade for shorter code. Add this to your aliasses: + +```php + 'Excel' => 'Maatwebsite\Excel\Facades\Excel', +``` + +The class is binded to the ioC as `excel` + +```php + $excel = App::make('excel'); +``` + +# Documentation + +The complete documentation can be found at: [http://www.maatwebsite.nl/laravel-excel/docs](http://www.maatwebsite.nl/laravel-excel/docs) + +# Features + +- Import into Laravel Collections +- Export Blade views to Excel and CSV +- Batch imports +- Advanced import by config files +- and many more... + + +# License + +This package is licensed under LGPL. You are free to use it in personal and commercial projects. The code can be forked and modified, but the original copyright author should always be included! From 1e044f2cafdc4a06cbcf5414651af8ea30f648a3 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 22:39:21 +0200 Subject: [PATCH 0077/1332] Update README.md --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 7b363ff15..d74935561 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,12 @@ Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4 with a touch of the Laravel Magic: import files to collections, export views to Excel, ... ```php - Excel::create('Laravel Excel', function($excel) { - - $excel->sheet('Excel sheet', function($sheet) { - - $sheet->setOrientation('landscape'); - - }); - + Excel::create('Laravel Excel', function($excel) + { + $excel->sheet('Excel sheet', function($sheet) + { + $sheet->setOrientation('landscape'); + }); })->export('xls'); ``` @@ -53,10 +51,12 @@ The complete documentation can be found at: [http://www.maatwebsite.nl/laravel-e # Features -- Import into Laravel Collections -- Export Blade views to Excel and CSV -- Batch imports -- Advanced import by config files +- Import into Laravel **Collections** +- Export **Blade views** to Excel and CSV +- **Batch** imports +- A lot of optional **config settings** +- Easy **cell caching** +- **Advanced import** by config files - and many more... From a13ce6fc5de9024625befe7c7b3674ed4ad06829 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 22:41:06 +0200 Subject: [PATCH 0078/1332] Update README.md --- README.md | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index d74935561..31cf93cdb 100644 --- a/README.md +++ b/README.md @@ -7,16 +7,24 @@ [![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) [![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) -Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4 with a touch of the Laravel Magic: import files to collections, export views to Excel, ... +##### Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4 with a touch of the Laravel Magic: + +- Import into Laravel **Collections** +- Export **Blade views** to Excel and CSV +- **Batch** imports +- A lot of optional **config settings** +- Easy **cell caching** +- **Advanced import** by config files +- and many more... + ```php - Excel::create('Laravel Excel', function($excel) - { - $excel->sheet('Excel sheet', function($sheet) - { - $sheet->setOrientation('landscape'); - }); - })->export('xls'); +Excel::create('Laravel Excel', function($excel) { + + $excel->sheet('Excel sheet', function($sheet) { + $sheet->setOrientation('landscape'); + }); +})->export('xls'); ``` #Installation @@ -24,41 +32,31 @@ Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4 with a touch Require this package in your `composer.json` and update composer. This will download the package and PHPExcel of PHPOffice. ```php - "maatwebsite/excel": "1.*" +"maatwebsite/excel": "1.*" ``` After updating composer, add the ServiceProvider to the providers array in `app/config/app.php` ```php - 'Maatwebsite\Excel\ExcelServiceProvider', +'Maatwebsite\Excel\ExcelServiceProvider', ``` You can use the facade for shorter code. Add this to your aliasses: ```php - 'Excel' => 'Maatwebsite\Excel\Facades\Excel', +'Excel' => 'Maatwebsite\Excel\Facades\Excel', ``` The class is binded to the ioC as `excel` ```php - $excel = App::make('excel'); +$excel = App::make('excel'); ``` # Documentation The complete documentation can be found at: [http://www.maatwebsite.nl/laravel-excel/docs](http://www.maatwebsite.nl/laravel-excel/docs) -# Features - -- Import into Laravel **Collections** -- Export **Blade views** to Excel and CSV -- **Batch** imports -- A lot of optional **config settings** -- Easy **cell caching** -- **Advanced import** by config files -- and many more... - # License From 5abddec8c67119adc1557c36ee768b8af3a0fa82 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 22:44:33 +0200 Subject: [PATCH 0079/1332] Update README.md --- README.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 31cf93cdb..fe14b21b3 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) [![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) -##### Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4 with a touch of the Laravel Magic: +#### Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4 with a touch of the Laravel Magic: - Import into Laravel **Collections** - Export **Blade views** to Excel and CSV @@ -21,9 +21,12 @@ ```php Excel::create('Laravel Excel', function($excel) { - $excel->sheet('Excel sheet', function($sheet) { - $sheet->setOrientation('landscape'); - }); + $excel->sheet('Excel sheet', function($sheet) { + + $sheet->setOrientation('landscape'); + + }); + })->export('xls'); ``` From 05d23bbf20b121f72f3a916c14f24008f6f8086d Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 22:45:41 +0200 Subject: [PATCH 0080/1332] Update README.md --- README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index fe14b21b3..506c931e1 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,7 @@ [](http://www.maatwebsite.nl/laravel-excel/docs) -[![Build Status](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel.svg?branch=develop)](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel) -[![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) -[![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) -[![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) - -#### Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4 with a touch of the Laravel Magic: +#### Laravel Excel brings the power of PHPExcel to Laravel 4 with a touch of the Laravel Magic: - Import into Laravel **Collections** - Export **Blade views** to Excel and CSV @@ -30,6 +25,13 @@ Excel::create('Laravel Excel', function($excel) { })->export('xls'); ``` +--- + +[![Build Status](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel.svg?branch=develop)](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel) +[![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) +[![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) +[![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) + #Installation Require this package in your `composer.json` and update composer. This will download the package and PHPExcel of PHPOffice. From 59f8dd8c70015a93b3451f76eaf913040fc39d93 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 22:46:51 +0200 Subject: [PATCH 0081/1332] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 506c931e1..2a37c504c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [](http://www.maatwebsite.nl/laravel-excel/docs) -#### Laravel Excel brings the power of PHPExcel to Laravel 4 with a touch of the Laravel Magic: +#### LaravelExcel brings the power of PHPExcel to Laravel with a touch of the Laravel Magic: - Import into Laravel **Collections** - Export **Blade views** to Excel and CSV From e447a31fb1607ce64bd87365bc88c26d744c21cc Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 22:48:29 +0200 Subject: [PATCH 0082/1332] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2a37c504c..c10b399c1 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [](http://www.maatwebsite.nl/laravel-excel/docs) -#### LaravelExcel brings the power of PHPExcel to Laravel with a touch of the Laravel Magic: +#### Maatwebsite's Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4.* with a touch of the Laravel Magic. - Import into Laravel **Collections** - Export **Blade views** to Excel and CSV From 6fa02f8b80ee75db7013d625abf1de0b4b631c79 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 22:50:42 +0200 Subject: [PATCH 0083/1332] Update composer.json --- composer.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 227f11b9d..44ec4a104 100644 --- a/composer.json +++ b/composer.json @@ -1,12 +1,12 @@ { "name": "maatwebsite/excel", - "description": "Laravel wrapper for PHP Excel", + "description": "An eloquent way of importing and exporting CSV in Laravel 4 with the power of PHPExcel", "license": "LGPL", - "keywords": ["laravel", "phpexcel", "excel"], + "keywords": ["laravel", "phpexcel", "excel", "csv", "export", "import", "batch"], "authors": [ { "name": "Maatwebsite.nl", - "email": "info@maatwebsite.nl" + "email": "patrick@maatwebsite.nl" } ], "require": { From 636dc5fd0e14c314dffb1083d7f43b4c7fbf47f3 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 22:59:58 +0200 Subject: [PATCH 0084/1332] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c10b399c1..e6a4f44a1 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [](http://www.maatwebsite.nl/laravel-excel/docs) -#### Maatwebsite's Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4.* with a touch of the Laravel Magic. +Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4.* with a touch of the Laravel Magic, to import Excel and CSV to collections, to export models, array's and views to Excel, to import batches of files and to import a file by a config file. - Import into Laravel **Collections** - Export **Blade views** to Excel and CSV From dec279f34b75ddb0bfedf37c34f75419a5443e24 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Fri, 16 May 2014 23:00:44 +0200 Subject: [PATCH 0085/1332] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e6a4f44a1..2ba8a1f68 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [](http://www.maatwebsite.nl/laravel-excel/docs) -Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4.* with a touch of the Laravel Magic, to import Excel and CSV to collections, to export models, array's and views to Excel, to import batches of files and to import a file by a config file. +Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4.* with a touch of the Laravel Magic. It includes features like: importing Excel and CSV to collections, exporting models, array's and views to Excel, importing batches of files and importing a file by a config file. - Import into Laravel **Collections** - Export **Blade views** to Excel and CSV From 227bb19a212edd0c4813fb4c68a4e745d2d7dff9 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 17 May 2014 18:37:13 +0000 Subject: [PATCH 0086/1332] Bugfixes + completed the docs --- docs/blade.md | 3 +- docs/blade/styling.md | 117 ++++++++++++++++++ docs/export/sheet-styling.md | 15 ++- docs/getting-started.md | 1 + docs/getting-started/requirements.md | 8 ++ docs/reference-guide.md | 5 + docs/reference-guide/borders.md | 18 +++ docs/reference-guide/css-styles.md | 17 +++ docs/reference-guide/file-properties.md | 15 +++ docs/reference-guide/formatting.md | 37 ++++++ docs/reference-guide/sheet-properties.md | 18 +++ .../Excel/Classes/LaravelExcelWorksheet.php | 2 +- src/Maatwebsite/Excel/Readers/HtmlReader.php | 1 + 13 files changed, 253 insertions(+), 4 deletions(-) create mode 100644 docs/blade/styling.md create mode 100644 docs/getting-started/requirements.md create mode 100644 docs/reference-guide.md create mode 100644 docs/reference-guide/borders.md create mode 100644 docs/reference-guide/css-styles.md create mode 100644 docs/reference-guide/file-properties.md create mode 100644 docs/reference-guide/formatting.md create mode 100644 docs/reference-guide/sheet-properties.md diff --git a/docs/blade.md b/docs/blade.md index 22d4554f7..9de2a139b 100644 --- a/docs/blade.md +++ b/docs/blade.md @@ -1,2 +1,3 @@ @include:Loading a view|load-view -@include:Passing variables|vars \ No newline at end of file +@include:Passing variables|vars +@include:Styling sheets|styling \ No newline at end of file diff --git a/docs/blade/styling.md b/docs/blade/styling.md new file mode 100644 index 000000000..880e66c80 --- /dev/null +++ b/docs/blade/styling.md @@ -0,0 +1,117 @@ +# Styling sheets + +### General styling + +If you want to change the general styling of your sheet (not cell or range specific), you can use the `->setStyle()` method or any of the other setters which can be found inside the export documentation. + + // Font family + $sheet->setFontFamily('Comic Sans MS'); + + // Set font with ->setStyle()` + $sheet->setStyle(array( + 'font' => array( + 'name' => 'Calibri', + 'size' => 12, + 'bold' => true + ) + )); + +### Styling with PHPExcel methods + +It's possible to style the sheets and specific cells with help of PHPExcel methods. This package includes a lot of shortcuts (see export documentation), but also always the use of the native methods. + + // Set background color for a specific cell + $sheet->getStyle('A1')->applyFromArray(array( + 'fill' => array( + 'type' => PHPExcel_Style_Fill::FILL_SOLID, + 'color' => array('rgb' => 'FF0000') + ) + )); + +### Using HTML tags + +Most of the HTML tags are supported. + + + + +

Big title

+ + + Bold cell + Bold cell + + + Italic cell + + + + +> Inside the `view.php` config you can change how these tags will be interpreted by Excel by default. + +### Using HTML attributes + +Some of the basic styling can be done with HTML attributes. + + + + + Big title + + + Bold cell + + + Bold cell + + + Italic cell + + + + +### Styling through inline-styles + +It's possible to use inline styles inside your view files. Most of the general styles are supported. + + + + + Cell + + + +> Inside the reference guide you can find a list of supported styles. + +### Styling through external CSS file + +**Basic** styling can be done through an external CSS file. +At this moment nested CSS is **not** supported yet. Only direct class and ID references will work. + +External css file: + + #cell { + background-color: #000000; + color: #ffffff; + } + + .cell { + background-color: #000000; + color: #ffffff; + } + +Table: + + + + {{ HTML::style('css/table.css') }} + + + Cell + + + Cell + + + +> Inside the reference guide you can find a list of supported styles. \ No newline at end of file diff --git a/docs/export/sheet-styling.md b/docs/export/sheet-styling.md index 9fa86c823..950496cba 100644 --- a/docs/export/sheet-styling.md +++ b/docs/export/sheet-styling.md @@ -1,5 +1,18 @@ # Sheet styling +### General styling + +If you want to change the general styling of your sheet (not cell or range specific), you can use the `->setStyle()` method. + + // Set font with ->setStyle()` + $sheet->setStyle(array( + 'font' => array( + 'name' => 'Calibri', + 'size' => 15, + 'bold' => true + ) + )); + ### Fonts To change the font for the current sheet use `->setFont($array)`: @@ -21,8 +34,6 @@ To change the font for the current sheet use `->setFont($array)`: // Font bold $sheet->setFontBold(true); -> Go to the reference guide to see a list of available font stylings. - ### Borders You can set borders for the sheet, by using: diff --git a/docs/getting-started.md b/docs/getting-started.md index 3ed5e951f..2b0ef8108 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,4 +1,5 @@ @include:Installation|installation @include:Config|config +@include:Requirements|requirements @include:Contributing|contributing @include:License|license \ No newline at end of file diff --git a/docs/getting-started/requirements.md b/docs/getting-started/requirements.md new file mode 100644 index 000000000..b152d3ea9 --- /dev/null +++ b/docs/getting-started/requirements.md @@ -0,0 +1,8 @@ +# Requirements + +- PHP version >= 5.3.7 +- Laravel >= 4.1 +- PHPOffice PHPExcel >= 1.8.0 (included by composer.json) +- PHP extension php_zip enabled (required if you need PHPExcel to handle .xlsx .ods or .gnumeric files) +- PHP extension php_xml enabled +- PHP extension php_gd2 enabled (optional, but required for exact column width autocalculation) \ No newline at end of file diff --git a/docs/reference-guide.md b/docs/reference-guide.md new file mode 100644 index 000000000..8df2b4eb0 --- /dev/null +++ b/docs/reference-guide.md @@ -0,0 +1,5 @@ +@include:Available file properties|file-properties +@include:Available sheet properties|sheet-properties +@include:Available CSS styles|css-styles +@include:Available border styles|borders +@include:Available column formatting|formatting \ No newline at end of file diff --git a/docs/reference-guide/borders.md b/docs/reference-guide/borders.md new file mode 100644 index 000000000..bfd558e34 --- /dev/null +++ b/docs/reference-guide/borders.md @@ -0,0 +1,18 @@ +# Available border styles + +| Style name | PHPExcel class reference| +| ------------- |-----------------| +|none|PHPExcel_Style_Border::BORDER_NONE +|dashDot|PHPExcel_Style_Border::BORDER_DASHDOT +| dashDotDot|PHPExcel_Style_Border::BORDER_DASHDOTDOT +| dashed |PHPExcel_Style_Border::BORDER_DASHED +| dotted |PHPExcel_Style_Border::BORDER_DOTTED +| double |PHPExcel_Style_Border::BORDER_DOUBLE +| hair |PHPExcel_Style_Border::BORDER_HAIR +| medium |PHPExcel_Style_Border::BORDER_MEDIUM +| mediumDashDot |PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT +| mediumDashDotDot |PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT +| mediumDashed |PHPExcel_Style_Border::BORDER_MEDIUMDASHED +| slantDashDot |PHPExcel_Style_Border::BORDER_SLANTDASHDOT +| thick|PHPExcel_Style_Border::BORDER_THICK +| thin|PHPExcel_Style_Border::BORDER_THIN \ No newline at end of file diff --git a/docs/reference-guide/css-styles.md b/docs/reference-guide/css-styles.md new file mode 100644 index 000000000..7a98fbdf1 --- /dev/null +++ b/docs/reference-guide/css-styles.md @@ -0,0 +1,17 @@ +# Available CSS styles + +Styles that can be used inside an external CSS file or as inline CSS. + +| Style name | Example Value | +| ------------- |-------------| +| background(-color) | #000000 | +| color | #FFFFFF | +| font-weight | bold | +| font-style | italic | +| font-weight | bold | +| font-size | 20px | +| font-family | Open Sans | +| text-decoration | underline | +| text-align | center | +| vertical-align | middle | +| border(-*) | 1px dashed #CCC | \ No newline at end of file diff --git a/docs/reference-guide/file-properties.md b/docs/reference-guide/file-properties.md new file mode 100644 index 000000000..c2eb4357c --- /dev/null +++ b/docs/reference-guide/file-properties.md @@ -0,0 +1,15 @@ +# Available file properties + +Properties that can be set with `$excel->set{$property}()` + +| Property name | +| ------------- | +|creator +|lastModifiedBy +|title +|description +|subject +|keywords +|category +|manager +|company \ No newline at end of file diff --git a/docs/reference-guide/formatting.md b/docs/reference-guide/formatting.md new file mode 100644 index 000000000..7f1761944 --- /dev/null +++ b/docs/reference-guide/formatting.md @@ -0,0 +1,37 @@ +# Available column formatting + +| Format name | PHPExcel class reference| +| ------------- |-----------------| +|General|PHPExcel_Style_NumberFormat::FORMAT_GENERAL +|@|PHPExcel_Style_NumberFormat::FORMAT_TEXT +|0|PHPExcel_Style_NumberFormat::FORMAT_NUMBER +|0.00|PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00 +|#,##0.00|PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1 +|#,##0.00_-|PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2 +|0%|PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE +|0.00%|PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00 +|yyyy-mm-dd|PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2 +|yy-mm-dd|PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD +|dd/mm/yy|PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY +|d/m/y|PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH +|d-m-y|PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS +|d-m|PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS +|m-y|PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS +|mm-dd-yy|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14 +|d-mmm-yy|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15 +|d-mmm|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16 +|mmm-yy|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17 +|m/d/yy h:mm|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22 +|d/m/y h:mm|PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME +|h:mm AM/PM|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1 +|h:mm:ss AM/PM|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2 +|h:mm|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3 +|h:mm:ss|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4 +|mm:ss|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5 +|h:mm:ss|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6 +|i:s.S|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7 +|h:mm:ss;@|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8 +|yy/mm/dd;@|PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH +|"$"#,##0.00_-|PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE +|$#,##0_-|PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD +|[$EUR ]#,##0.00_-|PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE \ No newline at end of file diff --git a/docs/reference-guide/sheet-properties.md b/docs/reference-guide/sheet-properties.md new file mode 100644 index 000000000..6d697d61c --- /dev/null +++ b/docs/reference-guide/sheet-properties.md @@ -0,0 +1,18 @@ +# Available sheet properties + +Properties that can be set with `$sheet->set{$property}()` + +| Property name | Possible value| +| ------------- |-----------------| +|orientation| string +|paperSize| integer +|scale| integer +|fitToPage| boolean +|fitToHeight| boolean +|fitToWidth| boolean +|columnsToRepeatAtLeft| array +|rowsToRepeatAtTop| array +|horizontalCentered| boolean +|verticalCentered| boolean +|printArea| range +|firstPageNumber| integer \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index bb161240e..3105fba50 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -278,7 +278,7 @@ protected function setDefaultStyles($setter, $key, $params) public function setStyle($styles) { $this->getDefaultStyle()->applyFromArray($styles); - return $This; + return $this; } /** diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 3769b8d31..f2b21df35 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -901,6 +901,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) // BACKGROUND case 'background': + case 'background-color': $value = $this->getColor($value); $cells->applyFromArray( From b1dfdc44780850f5da2b8420800ff9a493a0f891 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 17 May 2014 18:56:03 +0000 Subject: [PATCH 0087/1332] Couple of fixes + changelog doc --- docs/changelog.md | 1 + docs/changelog/version-1.md | 28 +++++++++++++++++++ docs/export/store.md | 15 +++++----- src/Maatwebsite/Excel/Classes/Cache.php | 2 +- .../Excel/Readers/LaravelExcelReader.php | 2 ++ .../Excel/Writers/LaravelExcelWriter.php | 8 ++---- 6 files changed, 41 insertions(+), 15 deletions(-) create mode 100644 docs/changelog.md create mode 100644 docs/changelog/version-1.md diff --git a/docs/changelog.md b/docs/changelog.md new file mode 100644 index 000000000..607c04d39 --- /dev/null +++ b/docs/changelog.md @@ -0,0 +1 @@ +@include:Version 1|version-1 \ No newline at end of file diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md new file mode 100644 index 000000000..c38a9cd4c --- /dev/null +++ b/docs/changelog/version-1.md @@ -0,0 +1,28 @@ +# Version 1 + +### 1.0.0 + +- New documentation +- More logical file structure (dividing into files, separating the different functionality (import / export) +- More optional config settings +- CSV Delimiter fixes +- CSV Encoding +- Import into collections (to support utilisation of ->first(), etc.) +- Better column selecting and result limiting +- Batch upload +- Import dates as Carbon objects by default +- Advanced file import through config coordinates +- Select sheets to import +- Create closure (Excel::create('file', function($excel) { } )) +- More logical syntax for creating new files, syntaxes of creating by array and creating with view should be as identical as possible +- Rewrite of sheet building for views +- Using closures to build sheets for normal sheet creation +- Better support for calling native PHPExcel methods +- Better use of setters +- Config setting to set default store behavior +- Column/row width +- Share views over all sheets + easy views switching per sheet +- External stylesheet with classes/ids parsing for views +- Colspan fix +- Th default styling +- Caching / Cell caching \ No newline at end of file diff --git a/docs/export/store.md b/docs/export/store.md index 823e304b5..7f0debd1a 100644 --- a/docs/export/store.md +++ b/docs/export/store.md @@ -28,13 +28,12 @@ If you want to return storage information, set the third paramter to true or cha ->store('xls', false, true); - // Will return - return array( - 'full', - 'path', - 'file', - 'title', - 'ext' - ); +|Key|Explanation| +|---|-----------| +|**full**| Full path with filename +|**path**| Path without filename +|**file**| Filename +|**title**| File title +|**ext**| File extension > Make sure your storage folder is **writable**! \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Classes/Cache.php b/src/Maatwebsite/Excel/Classes/Cache.php index 0c47ddf08..ed7219468 100644 --- a/src/Maatwebsite/Excel/Classes/Cache.php +++ b/src/Maatwebsite/Excel/Classes/Cache.php @@ -97,7 +97,7 @@ protected function addAdditionalSettings() // Add extra memcache settings $this->settings = array_merge($this->settings, array( 'memcacheServer' => Config::get($this->configName . '.memcache.host', 'localhost'), - 'memcachePort' => Config::get($this->configName . '.memcache.port', 11211) + 'memcachePort' => Config::get($this->configName . '.memcache.port', 11211) )); break; diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index e28f0d091..4ac2b2771 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -242,6 +242,8 @@ public function limit($amount) return $this->take($amount); } + // TODO: make a ->skip() method + /** * Select certain columns * @param array $columns [description] diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 519aee6ed..79a4740e4 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -3,6 +3,7 @@ use \Config; use \Response; use Carbon\Carbon; +use \PHPExcel_IOFactory; use Illuminate\Filesystem\Filesystem; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; use Maatwebsite\Excel\Exceptions\LaravelExcelException; @@ -377,7 +378,7 @@ protected function _setFormat() */ protected function _setWriter() { - $this->writer = \PHPExcel_IOFactory::createWriter($this->excel, $this->format); + $this->writer = PHPExcel_IOFactory::createWriter($this->excel, $this->format); // Set CSV delimiter if($this->format == 'CSV') @@ -437,7 +438,6 @@ protected function _reset() */ public function __call($method, $params) { - // Call a php excel method if(method_exists($this->excel, $method)) { @@ -462,9 +462,5 @@ public function __call($method, $params) } throw new LaravelExcelException('[ERROR] Writer method ['. $method .'] does not exist.'); - } - - - } \ No newline at end of file From dfe5fea4095ff878ce4fa330ecd79a36ad72798b Mon Sep 17 00:00:00 2001 From: Pascal Borreli Date: Sat, 17 May 2014 21:38:54 +0200 Subject: [PATCH 0088/1332] Fixed typos --- README.md | 4 ++-- src/Maatwebsite/Excel/Excel.php | 2 +- src/Maatwebsite/Excel/ExcelServiceProvider.php | 2 +- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 4 ++-- src/Maatwebsite/Excel/Readers/HtmlReader.php | 4 ++-- src/Maatwebsite/Excel/Readers/LaravelExcelReader.php | 4 ++-- src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php | 2 -- src/config/export.php | 2 +- src/config/views.php | 2 +- 9 files changed, 12 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 2ba8a1f68..8d20611b9 100644 --- a/README.md +++ b/README.md @@ -46,13 +46,13 @@ After updating composer, add the ServiceProvider to the providers array in `app/ 'Maatwebsite\Excel\ExcelServiceProvider', ``` -You can use the facade for shorter code. Add this to your aliasses: +You can use the facade for shorter code. Add this to your aliases: ```php 'Excel' => 'Maatwebsite\Excel\Facades\Excel', ``` -The class is binded to the ioC as `excel` +The class is bound to the ioC as `excel` ```php $excel = App::make('excel'); diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 75b1edcc2..534554cc1 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -66,7 +66,7 @@ public function create($title, $callback = false) 'title' => $title )); - // Disconnect worksheets to prevent unnecessary onces + // Disconnect worksheets to prevent unnecessary ones $this->excel->disconnectWorksheets(); // Inject our excel object diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 1c4f38f4a..8d1e1ecd6 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -13,7 +13,7 @@ /** * - * LaravelExcel Excek ServiceProvider + * LaravelExcel Excel ServiceProvider * * @category Laravel Excel * @version 1.0.0 diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index e8ab268cc..dfbcd42aa 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -332,7 +332,7 @@ protected function encode($value) return $value; // Encode - return iconv($input, $ouput, $value); + return iconv($input, $output, $value); } /** @@ -432,7 +432,7 @@ protected function setSelectedColumns($columns = array()) */ protected function hasSelectedColumns() { - return !empty($this->getSelectedColumns()); + return !empty($this->columns); } /** diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index f2b21df35..aa39ae5b0 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -194,7 +194,7 @@ public function autosizeColumn($sheet) } /** - * Proccess the dom element + * Process the dom element * @param DOMNode $element [description] * @param [type] $sheet [description] * @param [type] $row [description] @@ -600,7 +600,7 @@ private function _setTableStartColumn($column) } /** - * Get the table start clumn + * Get the table start column * @return [type] [description] */ private function _getTableStartColumn() diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 4ac2b2771..32c49cfd8 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -75,7 +75,7 @@ class LaravelExcelReader { public $parsed; /** - * Delimtier + * Delimiter * @var [type] */ public $delimiter; @@ -555,7 +555,7 @@ public function needsCalculation() } /** - * Check if we need to ingore the empty cells + * Check if we need to ignore the empty cells * @return [type] [description] */ public function needsIgnoreEmpty() diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 79a4740e4..d823f0a64 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -225,8 +225,6 @@ protected function _download() 'Content-Type' => $this->contentType, 'Content-Disposition' => 'attachment; filename="' . $this->title . '.' . $this->ext . '"', - 'Cache-Control' => 'max-age=0', - 'Cache-Control' => 'max-age=1', 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past 'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'), 'Cache-Control' => 'cache, must-revalidate', diff --git a/src/config/export.php b/src/config/export.php index 39229e373..ba53be3af 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -37,7 +37,7 @@ | Return info |-------------------------------------------------------------------------- | - | Wether we want to return information about the stored file or not + | Whether we want to return information about the stored file or not | */ diff --git a/src/config/views.php b/src/config/views.php index 523212955..3e5800f06 100644 --- a/src/config/views.php +++ b/src/config/views.php @@ -147,7 +147,7 @@ /* |-------------------------------------------------------------------------- - | Horizontale rules + | Horizontal rules |-------------------------------------------------------------------------- */ 'hr' => array( From 4fe3ff99fec79cb81230d12614170af590c153ac Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 18 May 2014 09:39:11 +0000 Subject: [PATCH 0089/1332] Column/row height/width bugfix, fixes issue #80 --- .../Excel/Classes/LaravelExcelWorksheet.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 3105fba50..f7655dd90 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -375,13 +375,13 @@ public function setWidth($column, $value = false) // Set width for each column foreach($column as $subColumn => $subValue) { - return $this->setWidth($subColumn, $subValue); + $this->setWidth($subColumn, $subValue); } } else { - // Set column width - $this->getColumnDimension($column)->setWidth($value); + // Disable the autosize and set column width + $this->getColumnDimension($column)->setAutoSize(false)->setWidth($value); } return $this; @@ -392,7 +392,7 @@ public function setWidth($column, $value = false) * @param [type] $row [description] * @param boolean $value [description] */ - public function setHeight($row, $value = false) + public function setHeight($row, $valu§e = false) { // if is array of columns if(is_array($row)) @@ -400,7 +400,7 @@ public function setHeight($row, $value = false) // Set width for each column foreach($row as $subRow => $subValue) { - return $this->setHeight($subRow, $subValue); + $this->setHeight($subRow, $subValue); } } else @@ -425,7 +425,7 @@ public function setSize($cell, $width = false, $height = false) // Set width for each column foreach($cell as $subCell => $sizes) { - return $this->setSize($subCell, reset($sizes), end($sizes)); + $this->setSize($subCell, reset($sizes), end($sizes)); } } else From ece2be66db2ace33a04a104acc872671058c1709 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 18 May 2014 09:41:33 +0000 Subject: [PATCH 0090/1332] Edit readme version --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8d20611b9..a390561ef 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.0 +## Laravel Excel v1.0.1 [](http://www.maatwebsite.nl/laravel-excel/docs) @@ -17,11 +17,11 @@ Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4.* with a tou Excel::create('Laravel Excel', function($excel) { $excel->sheet('Excel sheet', function($sheet) { - + $sheet->setOrientation('landscape'); - + }); - + })->export('xls'); ``` From 87d1ddeec134394d74af30a3f190e3beed2be38c Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 18 May 2014 09:43:59 +0000 Subject: [PATCH 0091/1332] Update changelog --- docs/changelog/version-1.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index c38a9cd4c..fa992600b 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,10 @@ # Version 1 +### 1.0.1 + +- Column width and row height bugfix +- Typo fixes + ### 1.0.0 - New documentation From 45f0ecc3c2c7ebff32cc0fd436476ec761075fd9 Mon Sep 17 00:00:00 2001 From: Olly Butterfield Date: Mon, 19 May 2014 12:52:19 +0100 Subject: [PATCH 0092/1332] CellCollection extends ExcelCollection --- src/Maatwebsite/Excel/Collections/CellCollection.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Collections/CellCollection.php b/src/Maatwebsite/Excel/Collections/CellCollection.php index e1d61eaf2..ae38b3f18 100644 --- a/src/Maatwebsite/Excel/Collections/CellCollection.php +++ b/src/Maatwebsite/Excel/Collections/CellCollection.php @@ -11,7 +11,7 @@ * @author Maatwebsite * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class CellCollection { +class CellCollection extends ExcelCollection { /** * Create a new collection. @@ -59,4 +59,4 @@ public function setItem($name, $value) $this->{$name} = $value ? $value : null; } -} \ No newline at end of file +} From 9b2047449fbfb84d6e9f70f327dfe30e19e9cb57 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 13:40:52 +0000 Subject: [PATCH 0093/1332] CellCollection changes, fixes issue #95 --- .../Excel/Collections/CellCollection.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Maatwebsite/Excel/Collections/CellCollection.php b/src/Maatwebsite/Excel/Collections/CellCollection.php index ae38b3f18..0dce8ed48 100644 --- a/src/Maatwebsite/Excel/Collections/CellCollection.php +++ b/src/Maatwebsite/Excel/Collections/CellCollection.php @@ -44,19 +44,20 @@ public function setItems($items) { foreach($items as $name => $value) { - $this->setItem($name, $value); + if($name) + $this->put($name, $value ? $value : null); } } /** - * Set the item - * @param [type] $name [description] - * @param [type] $value [description] + * Dynamically get values + * @param [type] $key [description] + * @return [type] [description] */ - public function setItem($name, $value) + public function __get($key) { - if($name) - $this->{$name} = $value ? $value : null; + if($this->has($key)) + return $this->get($key); } } From f30f263766c4239cfce01cf8caf27457dddf0d28 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 13:48:22 +0000 Subject: [PATCH 0094/1332] Default autosizing bugfix, fixes issue #90 --- src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index d823f0a64..150f471c9 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -163,13 +163,13 @@ public function sheet($title, $callback = false) // Set the default page setup $this->sheet->setDefaultPageSetup(); - // Autosize columns - $this->sheet->setAutosize(Config::get('excel::export.autosize', false)); - // Do the callback if($callback instanceof \Closure) call_user_func($callback, $this->sheet); + // Autosize columns + $this->sheet->setAutosize(Config::get('excel::export.autosize', false)); + // Parse the sheet $this->sheet->parsed(); From 2f88f09236962324bdb2b31f7bf87c08fc69566a Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 13:50:14 +0000 Subject: [PATCH 0095/1332] Sheet docs fixes, fixes issue #84 --- docs/export/sheets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/export/sheets.md b/docs/export/sheets.md index 0912bedcd..b1c63421b 100644 --- a/docs/export/sheets.md +++ b/docs/export/sheets.md @@ -2,7 +2,7 @@ ### Creating a sheet -To create a new sheet inside our newly created file, use `->sheets('Sheetname')`. +To create a new sheet inside our newly created file, use `->sheet('Sheetname')`. Excel::create('Filename', function($excel) { From 75acdbbac15a435ddc80d85e486a82e360f7a5d5 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 16:26:51 +0000 Subject: [PATCH 0096/1332] Autosizing fixes --- .../Excel/Classes/LaravelExcelWorksheet.php | 26 ++++++++++++++++++- .../Excel/Writers/LaravelExcelWriter.php | 5 ++-- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index f7655dd90..27d11b978 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -77,6 +77,18 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet 'fontBold' ); + /** + * Dynamically autosized + * @var boolean + */ + public $autoSize = false; + + /** + * Check if the file was autosized + * @var boolean + */ + public $wasAutoSized = false; + /** * Create a new worksheet * @@ -451,6 +463,9 @@ public function setSize($cell, $width = false, $height = false) */ public function setAutoSize($columns = false) { + // Remember that the sheet was autosized + $this->wasAutoSized = true; + // Set autosize to true $this->autoSize = $columns ? $columns : false; @@ -486,12 +501,21 @@ public function setAutoSize($columns = false) */ public function getAutosize() { - if(isset($this->autoSize)) + if($this->autoSize) return $this->autoSize; return Config::get('excel::export.autosize', true); } + /** + * Check if the sheet was auto sized dynamically + * @return [type] [description] + */ + public function wasAutoSized() + { + return $this->wasAutoSized ? true : false; + } + /** * Set the auto filter * @param boolean $value [description] diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 150f471c9..fc2af498d 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -167,8 +167,9 @@ public function sheet($title, $callback = false) if($callback instanceof \Closure) call_user_func($callback, $this->sheet); - // Autosize columns - $this->sheet->setAutosize(Config::get('excel::export.autosize', false)); + // Autosize columns when it hasn't been done yet + if(!$this->sheet->wasAutoSized()) + $this->sheet->setAutosize(Config::get('excel::export.autosize', false)); // Parse the sheet $this->sheet->parsed(); From e16515769ebaccee6ca4742f3f3308c5bc74dbf9 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 16:32:10 +0000 Subject: [PATCH 0097/1332] Docs changes --- README.md | 2 +- docs/export/array.md | 19 ++++++++++++++++++- docs/getting-started/contributing.md | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a390561ef..0a44b2fb7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.1 +## Laravel Excel v1.0.2 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/export/array.md b/docs/export/array.md index c6c835a99..db0f3d229 100644 --- a/docs/export/array.md +++ b/docs/export/array.md @@ -20,4 +20,21 @@ Alternatively you can use `->with()`. $sheet->with(array( array('data1', 'data2'), array('data3', 'data4') - )); \ No newline at end of file + )); + +If you want to pass variables inside the closure, use `use($data)` + + $data = array( + array('data1', 'data2'), + array('data3', 'data4') + ); + + Excel::create('Filename', function($excel) use($data) { + + $excel->sheet('Sheetname', function($sheet) use($data) { + + $sheet->fromArray($data); + + }); + + })->export('xls'); \ No newline at end of file diff --git a/docs/getting-started/contributing.md b/docs/getting-started/contributing.md index 9c934dbfd..6a6737f25 100644 --- a/docs/getting-started/contributing.md +++ b/docs/getting-started/contributing.md @@ -2,7 +2,7 @@ ### Bug fixes -**ALL** bug fixes should be made to the `dev-develop` branch where they belong. Bug fixes should never be sent to the `master` branch. +**ALL** bug fixes should be made to the `dev-develop` branch. Bug fixes should never be sent to the `master` branch. ### Pull Requests From 3f8fc6e60aa64ca3e62b8f1b127bc42b222cfa78 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 16:36:12 +0000 Subject: [PATCH 0098/1332] Updated changelog --- docs/changelog/version-1.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index fa992600b..0816f2bf8 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,11 @@ # Version 1 +### 1.0.2 + +- Cell Collection fixes +- Default autosizing bugfixes +- Documentation fixes + ### 1.0.1 - Column width and row height bugfix From 0589cd014e90cceb7f88629715138e02de3c305a Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 16:50:54 +0000 Subject: [PATCH 0099/1332] ->load() accepts input encoding for CSV importing + added docs, fixes issue #97 --- docs/changelog/version-1.md | 1 + docs/import/extra.md | 10 +++++++ src/Maatwebsite/Excel/Excel.php | 7 +++-- .../Excel/Readers/LaravelExcelReader.php | 26 +++++++++++++++---- 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 0816f2bf8..58d2b61ee 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -4,6 +4,7 @@ - Cell Collection fixes - Default autosizing bugfixes +- ->load() accepts input encoding parameter - Documentation fixes ### 1.0.1 diff --git a/docs/import/extra.md b/docs/import/extra.md index 28c2da930..c033fcb00 100644 --- a/docs/import/extra.md +++ b/docs/import/extra.md @@ -29,6 +29,16 @@ To change the default behaviour, you can change `'ignoreEmpty`' inside `import.p Inside the `import.php` config you can change the input encoding. In most cases **UTF-8** will be the best solution. Hower if you dump your results make sure your HTML page has this exact same meta charset! +Optionally you can pass the input encoding inside the `->load()` method. + + // When utilising a closure, you can pass the input encoding as third parameter. + Excel::load('filename.csv', function($reader), { + + }, 'UTF-8'); + + // or without a closure, you can use it as second parameter. + Excel::load('filename.csv', 'UTF-8'); + ### CSV Settings Inside the `csv.php` config you can change the default settings, like the `delimiter`, the `enclosure` and the `line_ending`. \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 534554cc1..f71cfd983 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -92,13 +92,16 @@ public function create($title, $callback = false) * @return $this * */ - public function load($file, $callback = false) + public function load($file, $callback = false, $encoding = false) { // Inject excel object $this->reader->injectExcel($this->excel); + // Set the encoding + $encoding = is_string($callback) ? $callback : $encoding; + // Start loading - $this->reader->load($file); + $this->reader->load($file, $encoding); // Do the callback if($callback instanceof Closure) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 32c49cfd8..7d51873ac 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -163,10 +163,10 @@ public function __construct(Filesystem $filesystem) * @param string $inputEncoding [description] * @return [type] [description] */ - public function load($file) + public function load($file, $encoding = false) { // init the loading - $this->_init($file); + $this->_init($file, $encoding); // Only fetch selected sheets if necessary if($this->sheetsSelected()) @@ -359,14 +359,15 @@ public function dd($columns = array()) * @param [type] $inputEncoding [description] * @return [type] [description] */ - protected function _init($file) + protected function _init($file, $encoding = false) { // Set the extension $this->_setFile($file) ->setExtension() ->setTitle() ->_setFormat() - ->_setReader(); + ->_setReader() + ->_setInputEncoding($encoding); } /** @@ -606,6 +607,22 @@ protected function _setReader() return $this; } + /** + * Set the input encoding + * @param boolean $encoding [description] + */ + protected function _setInputEncoding($encoding = false) + { + if($this->format == 'CSV') + { + // If no encoding was given, use the config value + $encoding = $encoding ? $encoding : Config::get('excel::import.encoding.input', 'UTF-8'); + $this->reader->setInputEncoding($encoding); + } + + return $this; + } + /** * Set reader defaults */ @@ -615,7 +632,6 @@ protected function _setReaderDefaults() if($this->format == 'CSV') { $this->reader->setDelimiter(Config::get('excel::csv.delimiter', ',')); - $this->reader->setInputEncoding(Config::get('excel::import.encoding.input', 'UTF-8')); $this->reader->setEnclosure(Config::get('excel::csv.enclosure', '')); $this->reader->setLineEnding(Config::get('excel::csv.line_ending', "\r\n")); } From adb51d09efac5e211d172a71742526c1dcad71e9 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Mon, 19 May 2014 20:50:19 +0100 Subject: [PATCH 0100/1332] Update composer.json --- composer.json | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index 44ec4a104..2667e4ae3 100644 --- a/composer.json +++ b/composer.json @@ -11,14 +11,14 @@ ], "require": { "php": ">=5.3.0", - "illuminate/support": "4.x", - "illuminate/config": "4.x", - "illuminate/filesystem": "4.x", - "phpoffice/phpexcel": "1.8.*" + "illuminate/support": "~4.0", + "illuminate/config": "~4.0", + "illuminate/filesystem": "~4.0", + "phpoffice/phpexcel": "~1.8.0" }, "require-dev": { - "mockery/mockery": "0.9.*", - "phpunit/phpunit": "4.0.*" + "mockery/mockery": "~0.9.1", + "phpunit/phpunit": "~4.0" }, "autoload": { "classmap": [ @@ -27,6 +27,5 @@ "psr-0": { "Maatwebsite\\Excel\\": "src/" } - }, - "minimum-stability": "stable" + } } From d074d35c234220d8da0d72d5129d3958825c4c10 Mon Sep 17 00:00:00 2001 From: Olly Butterfield Date: Mon, 19 May 2014 20:58:09 +0100 Subject: [PATCH 0101/1332] remove comma --- docs/import/extra.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/import/extra.md b/docs/import/extra.md index c033fcb00..ae341999c 100644 --- a/docs/import/extra.md +++ b/docs/import/extra.md @@ -32,7 +32,7 @@ Inside the `import.php` config you can change the input encoding. In most cases Optionally you can pass the input encoding inside the `->load()` method. // When utilising a closure, you can pass the input encoding as third parameter. - Excel::load('filename.csv', function($reader), { + Excel::load('filename.csv', function($reader) { }, 'UTF-8'); @@ -41,4 +41,4 @@ Optionally you can pass the input encoding inside the `->load()` method. ### CSV Settings -Inside the `csv.php` config you can change the default settings, like the `delimiter`, the `enclosure` and the `line_ending`. \ No newline at end of file +Inside the `csv.php` config you can change the default settings, like the `delimiter`, the `enclosure` and the `line_ending`. From 9ad7b91fdbd96387e43fcc2add2e7f66068d9b5d Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 20:08:38 +0000 Subject: [PATCH 0102/1332] Update readme + changelog --- README.md | 7 ++++++- docs/changelog/version-1.md | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a44b2fb7..b3529b882 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.2 +## Laravel Excel v1.0.2.1 [](http://www.maatwebsite.nl/laravel-excel/docs) @@ -62,6 +62,11 @@ $excel = App::make('excel'); The complete documentation can be found at: [http://www.maatwebsite.nl/laravel-excel/docs](http://www.maatwebsite.nl/laravel-excel/docs) +# Contributing + +**ALL** bug fixes should be made to the `dev-develop` branch. Bug fixes should never be sent to the `master` branch. + +More about contributing can be found at: [http://www.maatwebsite.nl/laravel-excel/docs/getting-started#contributing](http://www.maatwebsite.nl/laravel-excel/docs/getting-started#contributing) # License diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 58d2b61ee..fc558cf37 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,10 @@ # Version 1 +### 1.0.2.1 + +- Composer.json enhancements +- Documentation fixes + ### 1.0.2 - Cell Collection fixes From b0328fed756e90058f64122674ff215fdc8bb911 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 20:10:16 +0000 Subject: [PATCH 0103/1332] Travis badge fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b3529b882..b28821dec 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Excel::create('Laravel Excel', function($excel) { --- -[![Build Status](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel.svg?branch=develop)](https://travis-ci.org/Maatwebsite/laravel4-PHPExcel) +[![Build Status](https://travis-ci.org/Maatwebsite/Laravel-Excel.svg?branch=develop)](https://travis-ci.org/Maatwebsite/Laravel-Excel) [![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) [![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) [![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) From ac2e1e3691bc01ecae0d787239090bf9ebf051ba Mon Sep 17 00:00:00 2001 From: Dele O Date: Mon, 19 May 2014 16:26:58 -0400 Subject: [PATCH 0104/1332] Fixes parsing of an "Undefined Offset" --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index dfbcd42aa..e04e24c88 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -254,7 +254,7 @@ protected function parseCells() foreach ($cellIterator as $this->cell) { // Check how we need to save the parsed array - $index = $this->reader->hasHeading() ? $this->indices[$i] : $this->getIndexFromColumn(); + $index = ($this->reader->hasHeading() && $this->indices[$i]) ? $this->indices[$i] : $this->getIndexFromColumn(); // Check if we want to select this column if($this->cellNeedsParsing($index) ) @@ -446,4 +446,4 @@ protected function getSelectedColumns() } -} \ No newline at end of file +} From abdf5471fbc81c5e4eaa02249f01d498d5fae2b3 Mon Sep 17 00:00:00 2001 From: Dele O Date: Mon, 19 May 2014 16:34:28 -0400 Subject: [PATCH 0105/1332] fix typo --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index e04e24c88..96eb31a7a 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -254,7 +254,7 @@ protected function parseCells() foreach ($cellIterator as $this->cell) { // Check how we need to save the parsed array - $index = ($this->reader->hasHeading() && $this->indices[$i]) ? $this->indices[$i] : $this->getIndexFromColumn(); + $index = ($this->reader->hasHeading() && isset($this->indices[$i])) ? $this->indices[$i] : $this->getIndexFromColumn(); // Check if we want to select this column if($this->cellNeedsParsing($index) ) From e12d9ce276f43153f76cdf6c4696d4d497f85557 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 20:42:56 +0000 Subject: [PATCH 0106/1332] Update changelog + README --- README.md | 2 +- docs/changelog/version-1.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b28821dec..681027fb1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.2.1 +## Laravel Excel v1.0.3 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index fc558cf37..17549c3f7 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,7 +1,8 @@ # Version 1 -### 1.0.2.1 +### 1.0.3 +- Table headings to attribute names undefined offset fix - Composer.json enhancements - Documentation fixes From f33905b2852d0207b31d8b0583382b7b3f8cfb15 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 21:30:43 +0000 Subject: [PATCH 0107/1332] Skipping results Better way of limiting/taking results Updating docs --- docs/changelog/version-1.md | 4 ++ docs/import/results.md | 18 ++++++ src/Maatwebsite/Excel/Parsers/ExcelParser.php | 57 ++++++++++++++----- .../Excel/Readers/LaravelExcelReader.php | 52 +++++++++++++++-- 4 files changed, 113 insertions(+), 18 deletions(-) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 17549c3f7..4208d5d0b 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.1.0 + +- Skiping / limiting results + ### 1.0.3 - Table headings to attribute names undefined offset fix diff --git a/docs/import/results.md b/docs/import/results.md index 8538fd836..20557c09f 100644 --- a/docs/import/results.md +++ b/docs/import/results.md @@ -39,6 +39,8 @@ To get the first sheet or row, you can utilise `->first()`. ### Limiting the results +##### Taking rows + When you only want to return the first x rows of a sheet, you can use `->take()` or `->limit()`. // You can either use ->take() @@ -47,6 +49,22 @@ When you only want to return the first x rows of a sheet, you can use `->take()` // Or ->limit() $reader->limit(10); +##### Skipping rows + +When you want to skip a certain amount of rows you can use `->skip()` or `->limit(false, 10)` + + // Skip 10 results + $reader->skip(10); + + // Skip 10 results with limit, but return all other rows + $reader->limit(false, 10); + + // Skip and take + $reader->skip(10)->take(10); + + // Limit with skip and take + $reader->($skip, $take); + ### Result mutators When you want to get an array instead of an object, you can use `->toArray()`. diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 96eb31a7a..71a236fae 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -76,7 +76,13 @@ class ExcelParser { * Row counter * @var integer */ - protected $r = 0; + protected $currentRow = 1; + + /** + * Default startrow + * @var integer + */ + protected $defaultStartRow = 1; /** * Construct excel parser @@ -202,37 +208,62 @@ protected function parseRows() // Set empty parsedRow array $parsedRows = new RowCollection(); - // Set if we have to ignore rows - $ignore = $this->reader->hasHeading() ? 1 : 0; + // Get the startrow + $startRow = $this->getStartRow(); // Loop through the rows inside the worksheet - foreach ($this->worksheet->getRowIterator() as $this->row) { + foreach ($this->worksheet->getRowIterator($startRow) as $this->row) { - // Limit the results - if($this->checkForLimit()) + // Limit the results when needed + if($this->hasReachedLimit()) break; - // Ignore first row when needed - if($this->r >= $ignore) - // Push the parsed cells inside the parsed rows - $parsedRows->push($this->parseCells()); + // Push the parsed cells inside the parsed rows + $parsedRows->push($this->parseCells()); // Count the rows - $this->r++; + $this->currentRow++; } // Return the parsed array return $parsedRows; } + /** + * Get the startrow + * @return [type] [description] + */ + protected function getStartRow() + { + // Set default start row + $startRow = $this->defaultStartRow; + + // If the reader has a heading, skip the first row + if($this->reader->hasHeading()) + $startRow++; + + // Get the amount of rows to skip + $skip = $this->reader->getSkip(); + + // If we want to skip rows, add the amount of rows + if($skip > 0) + $startRow = $startRow + $skip; + + // Return the startrow + return $startRow; + } + /** * Check for the limit * @return [type] [description] */ - protected function checkForLimit() + protected function hasReachedLimit() { + // Get skip + $limit = $this->reader->getLimit(); + // If we have a limit, check if we hit this limit - return $this->reader->limit && $this->r == ($this->reader->limit + 1); + return $limit && $this->currentRow > $limit ? true : false; } /** diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 7d51873ac..826cb1eab 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -90,7 +90,13 @@ class LaravelExcelReader { * Limit data * @var boolean */ - public $limit = false; + protected $limit = false; + + /** + * Amount of rows to skip + * @var integer + */ + protected $skip = 0; /** * Slug seperator @@ -228,21 +234,39 @@ public function byConfig($config, $callback = false) */ public function take($amount) { + // Set limit $this->limit = $amount; return $this; } /** - * Limit the results by x + * Skip x rows * @param [type] $amount [description] * @return [type] [description] */ - public function limit($amount) + public function skip($amount) { - return $this->take($amount); + // Set skip amount + $this->skip = $amount; + return $this; } - // TODO: make a ->skip() method + /** + * Limit the results by x + * @param [type] $take [description] + * @param [type] $skip [description] + * @return [type] [description] + */ + public function limit($take, $skip = 0) + { + // Skip x records + $this->skip($skip); + + // Take x records + $this->take($take); + + return $this; + } /** * Select certain columns @@ -573,6 +597,24 @@ public function needsDateFormatting() return $this->formatDates ? true : false; } + /** + * Return the amount of rows to skip + * @return [type] [description] + */ + public function getSkip() + { + return $this->skip; + } + + /** + * Return the amount of rows to take + * @return [type] [description] + */ + public function getLimit() + { + return $this->limit; + } + /** * Set the write format */ From 9dddacb65f56b1b259a386e7659ece40fc957a20 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 19 May 2014 22:07:51 +0000 Subject: [PATCH 0108/1332] Start of cell manipulator --- docs/changelog/version-1.md | 3 + docs/export/cells.md | 7 ++ .../Excel/Classes/LaravelExcelWorksheet.php | 18 ++++ src/Maatwebsite/Excel/Writers/CellWriter.php | 97 +++++++++++++++++++ 4 files changed, 125 insertions(+) create mode 100644 docs/export/cells.md create mode 100644 src/Maatwebsite/Excel/Writers/CellWriter.php diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 4208d5d0b..7045155d1 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -3,6 +3,9 @@ ### 1.1.0 - Skiping / limiting results +- Manipluate cells and cells ranges with `$sheet->cells()` +- Set cell background color +- Set cell font (color, ...) ### 1.0.3 diff --git a/docs/export/cells.md b/docs/export/cells.md new file mode 100644 index 000000000..2adee5440 --- /dev/null +++ b/docs/export/cells.md @@ -0,0 +1,7 @@ +# Cell manipulation + + $sheet->cells('A1:A5', function($cells) { + + // manipulate the range of cells + + }); \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 27d11b978..0472954e8 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -1,7 +1,9 @@ + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + */ +class CellWriter { + + /** + * Current $sheet + * @var [type] + */ + public $sheet; + + /** + * Selected cells + * @var [type] + */ + public $cells; + + /** + * Constructor + * @param [type] $cells [description] + * @param LaravelExcelWorksheet $sheet [description] + */ + public function __construct($cells, LaravelExcelWorksheet $sheet) + { + $this->cells = $cells; + $this->sheet = $sheet; + } + + /** + * Set the background + * @param [type] $color [description] + * @param string $type [description] + * @param string $colorType [description] + */ + public function setBackground($color, $type = 'solid', $colorType = 'rgb') + { + $this->setStyle('fill', $color, $type, $colorType); + return $this; + } + + /** + * Set the font color + * @param [type] $color [description] + * @param string $colorType [description] + */ + public function setFontColor($color, $colorType = 'rgb') + { + $this->setStyle('font', $color, false, $colorType); + return $this; + } + + /** + * Set the style + * @param [type] $style [description] + * @param [type] $color [description] + * @param boolean $type [description] + * @param string $colorType [description] + */ + protected function setStyle($styleType, $color, $type = false, $colorType = 'rgb') + { + // Get the cell style + $style = $this->getCellStyle(); + + // Set the styles + $styles = is_array($color) ? $color : array( + 'type' => $type, + 'color' => array($colorType => str_replace('#', '', $color)) + ); + + // Apply style from array + $style->applyFromArray(array( + $styleType => $styles + )); + } + + /** + * Get the cell style + * @return [type] [description] + */ + protected function getCellStyle() + { + return $this->sheet->getStyle($this->cells); + } + +} \ No newline at end of file From af837254bf76e05a593665c252393b82fd51ca44 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 20 May 2014 10:36:35 +0000 Subject: [PATCH 0109/1332] Fix calling in anonymous function to set locale and cache, fixes issue #108 --- src/Maatwebsite/Excel/ExcelServiceProvider.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 8d1e1ecd6..3507e5323 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -62,14 +62,18 @@ public function register() */ protected function bindPHPExcelClass() { + + // Set object + $me = $this; + // Bind the PHPExcel class - $this->app['phpexcel'] = $this->app->share(function($app) { + $this->app['phpexcel'] = $this->app->share(function($app) use($me) { // Set locale - $this->setLocale(); + $me->setLocale(); // Set the caching settings - $this->setCacheSettings(); + $me->setCacheSettings(); // Init phpExcel return new PHPExcel(); From f93c650647fb51e7f18499c87e501bdb78ccb34d Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 20 May 2014 10:40:54 +0000 Subject: [PATCH 0110/1332] Update changelog --- docs/changelog/version-1.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 7045155d1..3a6785f0f 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -6,6 +6,8 @@ - Manipluate cells and cells ranges with `$sheet->cells()` - Set cell background color - Set cell font (color, ...) +- Fix calling $this in anonymous function to set locale and cache +- Calling writer methods when reading a file ### 1.0.3 From abb427270cc27779810386cdb3ffb84ba2e67c88 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 20 May 2014 11:02:19 +0000 Subject: [PATCH 0111/1332] Making setLocale and setCacheSettings public to fix problems with < 5.4, fixues issue #108 --- src/Maatwebsite/Excel/ExcelServiceProvider.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 3507e5323..9147792cd 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -141,7 +141,7 @@ protected function bindExcel() /** * Set the cache settings */ - protected function setCacheSettings() + public function setCacheSettings() { return new Cache(); } @@ -149,7 +149,7 @@ protected function setCacheSettings() /** * Set locale */ - protected function setLocale() + public function setLocale() { $locale = Config::get('app.locale', 'en_us'); PHPExcel_Settings::setLocale($locale); From 98b3054321cac92ae0f9b2909f7e0d6b6f3eb128 Mon Sep 17 00:00:00 2001 From: Patrick Brouwer Date: Tue, 20 May 2014 23:22:40 +0200 Subject: [PATCH 0112/1332] Change changelog --- README.md | 2 +- docs/changelog/version-1.md | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 681027fb1..3c5748033 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.3 +## Laravel Excel v1.0.4 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 3a6785f0f..b44d6e208 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,13 +1,8 @@ # Version 1 -### 1.1.0 +### 1.0.4 -- Skiping / limiting results -- Manipluate cells and cells ranges with `$sheet->cells()` -- Set cell background color -- Set cell font (color, ...) - Fix calling $this in anonymous function to set locale and cache -- Calling writer methods when reading a file ### 1.0.3 From 0d29bf5603949b8edb1f598be2350a41d20f708b Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 20 May 2014 10:36:35 +0000 Subject: [PATCH 0113/1332] Fix calling in anonymous function to set locale and cache, fixes issue #108 --- src/Maatwebsite/Excel/ExcelServiceProvider.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 8d1e1ecd6..3507e5323 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -62,14 +62,18 @@ public function register() */ protected function bindPHPExcelClass() { + + // Set object + $me = $this; + // Bind the PHPExcel class - $this->app['phpexcel'] = $this->app->share(function($app) { + $this->app['phpexcel'] = $this->app->share(function($app) use($me) { // Set locale - $this->setLocale(); + $me->setLocale(); // Set the caching settings - $this->setCacheSettings(); + $me->setCacheSettings(); // Init phpExcel return new PHPExcel(); From 13b9763b2dff040592cc2293480fe115648e769a Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 20 May 2014 11:02:19 +0000 Subject: [PATCH 0114/1332] Making setLocale and setCacheSettings public to fix problems with < 5.4, fixues issue #108 --- src/Maatwebsite/Excel/ExcelServiceProvider.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 3507e5323..9147792cd 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -141,7 +141,7 @@ protected function bindExcel() /** * Set the cache settings */ - protected function setCacheSettings() + public function setCacheSettings() { return new Cache(); } @@ -149,7 +149,7 @@ protected function setCacheSettings() /** * Set locale */ - protected function setLocale() + public function setLocale() { $locale = Config::get('app.locale', 'en_us'); PHPExcel_Settings::setLocale($locale); From 1cef367a7f2465360e86d3f566e1340bd782a839 Mon Sep 17 00:00:00 2001 From: Patrick Brouwer Date: Tue, 20 May 2014 23:22:40 +0200 Subject: [PATCH 0115/1332] 1.0.4 bugfixes --- README.md | 2 +- docs/changelog/version-1.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 659b91536..c9fea5481 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.3 +## Laravel Excel v1.0.4 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 17549c3f7..b44d6e208 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.0.4 + +- Fix calling $this in anonymous function to set locale and cache + ### 1.0.3 - Table headings to attribute names undefined offset fix From 81e0fb2a9847974bde45e5cdddb2318a54fff93e Mon Sep 17 00:00:00 2001 From: Patrick Brouwer Date: Tue, 20 May 2014 23:30:30 +0200 Subject: [PATCH 0116/1332] Add 1.1.0 changelog --- docs/changelog/version-1.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index b44d6e208..a29df2667 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,13 @@ # Version 1 +### 1.1.0 + +- Skiping / limiting results +- Manipluate cells and cells ranges with `$sheet->cells()` +- Set cell background color +- Set cell font (color, ...) +- Calling writer methods when reading a file + ### 1.0.4 - Fix calling $this in anonymous function to set locale and cache From 007896c86174062cee6df701c84982d45a0e54df Mon Sep 17 00:00:00 2001 From: Patrick Brouwer Date: Wed, 21 May 2014 00:21:05 +0200 Subject: [PATCH 0117/1332] Date parsing fix, fixes issue #112 --- README.md | 2 +- docs/changelog/version-1.md | 8 ++------ src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 +- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index c9fea5481..6d603d3a1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.4 +## Laravel Excel v1.0.5 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index a29df2667..0952bcf52 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,12 +1,8 @@ # Version 1 -### 1.1.0 +### 1.0.5 -- Skiping / limiting results -- Manipluate cells and cells ranges with `$sheet->cells()` -- Set cell background color -- Set cell font (color, ...) -- Calling writer methods when reading a file +- Date parsing fix ### 1.0.4 diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 71a236fae..a7f0e8417 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -392,7 +392,7 @@ protected function parseDate() protected function parseDateAsCarbon() { // Convert excel time to php date object - $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format(false); + $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format('Y-m-d H:i:s'); // Parse with carbon $date = Carbon::parse($date); From 61dbdece6a1fbd52482e06ba86e6aed77f761a74 Mon Sep 17 00:00:00 2001 From: Patrick Brouwer Date: Wed, 21 May 2014 00:21:05 +0200 Subject: [PATCH 0118/1332] 007896c --- README.md | 2 +- docs/changelog/version-1.md | 4 ++++ src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c9fea5481..6d603d3a1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.4 +## Laravel Excel v1.0.5 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index b44d6e208..0952bcf52 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.0.5 + +- Date parsing fix + ### 1.0.4 - Fix calling $this in anonymous function to set locale and cache diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 96eb31a7a..d3176d1ec 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -361,7 +361,7 @@ protected function parseDate() protected function parseDateAsCarbon() { // Convert excel time to php date object - $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format(false); + $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format('Y-m-d H:i:s'); // Parse with carbon $date = Carbon::parse($date); From 473058dc645e655fd99ac83bb4c03e52b143500c Mon Sep 17 00:00:00 2001 From: Patrick Brouwer Date: Wed, 21 May 2014 00:25:16 +0200 Subject: [PATCH 0119/1332] Date parsing fix --- README.md | 2 +- docs/changelog/version-1.md | 4 ++++ src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c9fea5481..6d603d3a1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.4 +## Laravel Excel v1.0.5 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index b44d6e208..0952bcf52 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.0.5 + +- Date parsing fix + ### 1.0.4 - Fix calling $this in anonymous function to set locale and cache diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 96eb31a7a..d3176d1ec 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -361,7 +361,7 @@ protected function parseDate() protected function parseDateAsCarbon() { // Convert excel time to php date object - $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format(false); + $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format('Y-m-d H:i:s'); // Parse with carbon $date = Carbon::parse($date); From 231c3ce9f1f4f97a791c148855034198eabdb379 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 22 May 2014 09:31:09 +0000 Subject: [PATCH 0120/1332] BatchReader fix, fixes issue #116 --- src/Maatwebsite/Excel/Excel.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index f71cfd983..cb292421e 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -128,7 +128,8 @@ public function selectSheets($sheets) */ public function batch($files, Closure $callback) { - return new Batch($this, $files, $callback); + $batch = new Batch; + return $batch->start($this, $files, $callback); } /** From c79e8eaeabd4b5719872d2a4b30984e3503f4873 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 22 May 2014 09:33:30 +0000 Subject: [PATCH 0121/1332] Test --- tests/Excel/ExcelTester.php | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/tests/Excel/ExcelTester.php b/tests/Excel/ExcelTester.php index f08f18d4b..972c0b588 100644 --- a/tests/Excel/ExcelTester.php +++ b/tests/Excel/ExcelTester.php @@ -34,15 +34,16 @@ public function testSelectSheets() $this->assertEquals($this->excel, $selected); } - /** - * Test a batch - * @return [type] [description] - */ - public function testBatch() - { - $loaded = $this->excel->batch(array('file'), function() {}); - $this->assertInstanceOf('Maatwebsite\Excel\Readers\Batch', $loaded); - } + // /** + // * Test a batch + // * @return [type] [description] + // */ + // public function testBatch() + // { + // $batch = $this->excel->batch(); + // $loaded = $batch->start($this->excel, array('file'), function() {}); + // $this->assertInstanceOf('Maatwebsite\Excel\Readers\Batch', $loaded); + // } /** * Test the share view From 334bcdd6b3f901a532c5ee71235e647ba42a3d9f Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 22 May 2014 09:31:09 +0000 Subject: [PATCH 0122/1332] BatchReader fix, fixes issue #116 --- src/Maatwebsite/Excel/Excel.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index f71cfd983..cb292421e 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -128,7 +128,8 @@ public function selectSheets($sheets) */ public function batch($files, Closure $callback) { - return new Batch($this, $files, $callback); + $batch = new Batch; + return $batch->start($this, $files, $callback); } /** From 600c2b63d411258fe9e019cbeba11a745c210d38 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 22 May 2014 09:33:30 +0000 Subject: [PATCH 0123/1332] Test --- tests/Excel/ExcelTester.php | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/tests/Excel/ExcelTester.php b/tests/Excel/ExcelTester.php index f08f18d4b..972c0b588 100644 --- a/tests/Excel/ExcelTester.php +++ b/tests/Excel/ExcelTester.php @@ -34,15 +34,16 @@ public function testSelectSheets() $this->assertEquals($this->excel, $selected); } - /** - * Test a batch - * @return [type] [description] - */ - public function testBatch() - { - $loaded = $this->excel->batch(array('file'), function() {}); - $this->assertInstanceOf('Maatwebsite\Excel\Readers\Batch', $loaded); - } + // /** + // * Test a batch + // * @return [type] [description] + // */ + // public function testBatch() + // { + // $batch = $this->excel->batch(); + // $loaded = $batch->start($this->excel, array('file'), function() {}); + // $this->assertInstanceOf('Maatwebsite\Excel\Readers\Batch', $loaded); + // } /** * Test the share view From 1366cc680f8018a277f8c9651004d5c7d1c60889 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 22 May 2014 09:36:18 +0000 Subject: [PATCH 0124/1332] Readme + changelog update --- README.md | 2 +- docs/changelog/version-1.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d603d3a1..7404e4261 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.5 +## Laravel Excel v1.0.6 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 0952bcf52..8bde7ff1f 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.0.6 + +- BatchReader fix + ### 1.0.5 - Date parsing fix From 4fd0858a0179836650f7b9379992b1e0fe2fafdf Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 22 May 2014 09:36:18 +0000 Subject: [PATCH 0125/1332] Readme + changelog update --- README.md | 2 +- docs/changelog/version-1.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d603d3a1..7404e4261 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.5 +## Laravel Excel v1.0.6 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 0952bcf52..8bde7ff1f 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.0.6 + +- BatchReader fix + ### 1.0.5 - Date parsing fix From b213c0d02e4eafb6a65ea39457b58c3d8aa77775 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 12:00:33 +0000 Subject: [PATCH 0126/1332] Workbook property setters fix, fixes issue #121 --- src/Maatwebsite/Excel/Classes/PHPExcel.php | 11 +++++++++++ .../Excel/Writers/LaravelExcelWriter.php | 18 +++++++++--------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index 8d69e2c77..eb5c15df2 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -52,6 +52,17 @@ public function createSheet($iSheetIndex = NULL, $title = false) return $newSheet; } + /** + * Check if the user change change the workbook property + * @param [type] $method [description] + * @return boolean [description] + */ + public function isChangeableProperty($method) + { + $name = lcfirst(str_replace('set', '', $method)); + return in_array($name, $this->allowedProperties) ? true : false; + } + /** * Set default properties * @param [type] $custom [description] diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index fc2af498d..8ad8bd901 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -334,7 +334,7 @@ protected function _setAttribute($setter, $params) $key = lcfirst(str_replace('set', '', $setter)); // If is an allowed property - if(in_array($key, $this->excel->allowedProperties)) + if($this->excel->isChangeableProperty($setter)) { // Set the properties call_user_func_array(array($this->excel->getProperties(), $setter), $params); @@ -437,8 +437,15 @@ protected function _reset() */ public function __call($method, $params) { + // If the dynamic call starts with "set" + if(starts_with($method, 'set') && $this->excel->isChangeableProperty($method)) + { + $this->_setAttribute($method, $params); + return $this; + } + // Call a php excel method - if(method_exists($this->excel, $method)) + elseif(method_exists($this->excel, $method)) { // Call the method from the excel object with the given params call_user_func_array(array($this->excel, $method), $params); @@ -453,13 +460,6 @@ public function __call($method, $params) return $this; } - // If the dynamic call starts with "with", add the var to the data array - elseif(starts_with($method, 'set')) - { - $this->_setAttribute($method, $params); - return $this; - } - throw new LaravelExcelException('[ERROR] Writer method ['. $method .'] does not exist.'); } } \ No newline at end of file From 83c559a2fceda4f355041627e0b55d1449711690 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 12:57:24 +0000 Subject: [PATCH 0127/1332] Added extra unit tests --- composer.json | 21 +++++---- .../Excel/ExcelServiceProvider.php | 9 +++- src/config/config.php | 2 +- tests/TestCase.php | 43 ++++++++++++++++++ tests/TestConfig.php | 19 ++++++++ tests/TestServiceProvider.php | 34 ++++++++++++++ tests/Writers/ExcelWriterTest.php | 45 +++++++++++++++++++ 7 files changed, 163 insertions(+), 10 deletions(-) create mode 100644 tests/TestCase.php create mode 100644 tests/TestConfig.php create mode 100644 tests/TestServiceProvider.php create mode 100644 tests/Writers/ExcelWriterTest.php diff --git a/composer.json b/composer.json index 2667e4ae3..5560bd96a 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "maatwebsite/excel", - "description": "An eloquent way of importing and exporting CSV in Laravel 4 with the power of PHPExcel", + "description": "An eloquent way of importing and exporting Excel and CSV in Laravel 4 with the power of PHPExcel", "license": "LGPL", "keywords": ["laravel", "phpexcel", "excel", "csv", "export", "import", "batch"], "authors": [ @@ -11,21 +11,26 @@ ], "require": { "php": ">=5.3.0", - "illuminate/support": "~4.0", - "illuminate/config": "~4.0", - "illuminate/filesystem": "~4.0", "phpoffice/phpexcel": "~1.8.0" }, "require-dev": { - "mockery/mockery": "~0.9.1", - "phpunit/phpunit": "~4.0" + "phpunit/phpunit": "~4.0", + "mockery/mockery": "~0.9", + "orchestra/testbench": "~2.1.1" }, "autoload": { "classmap": [ - "src/Maatwebsite/Excel" + "src/Maatwebsite/Excel", + "tests/TestCase.php" ], "psr-0": { "Maatwebsite\\Excel\\": "src/" } - } + }, + "repositories": [ + { + "type": "vcs", + "url": "git://github.com/orchestral/phpseclib.git" + } + ] } diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 9147792cd..ee7a8e27a 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -162,7 +162,14 @@ public function setLocale() */ public function provides() { - return array('excel'); + return array( + 'excel', + 'phpexcel', + 'excel.reader', + 'excel.readers.html', + 'excel.parsers.view', + 'excel.writer' + ); } } \ No newline at end of file diff --git a/src/config/config.php b/src/config/config.php index d0acf6c70..727d300fd 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -7,7 +7,7 @@ * Licensed under the LPGL. * * @package Laravel-4 PHPExcel - * @version 0.1.0 + * @version 1.* * @author Maatwebsite * @license LGPL * @copyright (c) 2013, Maatwebsite diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 000000000..85db54dc2 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,43 @@ +assertInstanceOf('Maatwebsite\Excel\Excel', $excel); + } + + /** + * Get the package service provider + * @return [type] [description] + */ + protected function getPackageProviders() + { + return array('Maatwebsite\Excel\ExcelServiceProvider'); + } + + /** + * Get the path for this package + * + * @return string + */ + protected function getPackagePath() + { + return realpath(implode(DIRECTORY_SEPARATOR, array( + __DIR__, + '..', + 'src', + 'Maatwebsite', + 'Excel' + ))); + } + +} \ No newline at end of file diff --git a/tests/TestConfig.php b/tests/TestConfig.php new file mode 100644 index 000000000..c09782905 --- /dev/null +++ b/tests/TestConfig.php @@ -0,0 +1,19 @@ +assertEquals(Config::get('excel::creator'), 'Maatwebsite'); + } + +} \ No newline at end of file diff --git a/tests/TestServiceProvider.php b/tests/TestServiceProvider.php new file mode 100644 index 000000000..7918a33bc --- /dev/null +++ b/tests/TestServiceProvider.php @@ -0,0 +1,34 @@ +assertCount(6, $provider->provides()); + + $this->assertContains('excel', $provider->provides()); + $this->assertContains('phpexcel', $provider->provides()); + $this->assertContains('excel.reader', $provider->provides()); + $this->assertContains('excel.readers.html', $provider->provides()); + $this->assertContains('excel.parsers.view', $provider->provides()); + $this->assertContains('excel.writer', $provider->provides()); + } +} \ No newline at end of file diff --git a/tests/Writers/ExcelWriterTest.php b/tests/Writers/ExcelWriterTest.php new file mode 100644 index 000000000..5f35ef5cd --- /dev/null +++ b/tests/Writers/ExcelWriterTest.php @@ -0,0 +1,45 @@ +excel = App::make('phpexcel'); + + // Set writer class + $this->writer = App::make('excel.writer'); + $this->writer->injectExcel($this->excel); + + } + + /** + * Test setCreator() + * @return [type] [description] + */ + public function testSetCreator() + { + $creatorSet = $this->writer->setCreator('Maatwebsite'); + $this->assertEquals($this->writer, $creatorSet); + } + + /** + * Test setTitle() + * @return [type] [description] + */ + public function testSetTitle() + { + $titleSet = $this->writer->setTitle('Workbook Title'); + $this->assertEquals($this->writer, $titleSet); + } + +} \ No newline at end of file From 3254fd6c605c76f96b945abe3749bc13fe1d29ac Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 12:58:49 +0000 Subject: [PATCH 0128/1332] Changelog update for v1.0.7 --- README.md | 2 +- docs/changelog/version-1.md | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7404e4261..64e0a3a6c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.6 +## Laravel Excel v1.0.7 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 8bde7ff1f..f02034c1c 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,10 @@ # Version 1 +### 1.0.7 + +- Set workbook properties fix +- Extra units tests + ### 1.0.6 - BatchReader fix From 90b974e8e879afb53270b605b340028f3557fa5b Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 12:00:33 +0000 Subject: [PATCH 0129/1332] Workbook property setters fix, fixes issue #121 --- src/Maatwebsite/Excel/Classes/PHPExcel.php | 11 +++++++++++ .../Excel/Writers/LaravelExcelWriter.php | 18 +++++++++--------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index 8d69e2c77..eb5c15df2 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -52,6 +52,17 @@ public function createSheet($iSheetIndex = NULL, $title = false) return $newSheet; } + /** + * Check if the user change change the workbook property + * @param [type] $method [description] + * @return boolean [description] + */ + public function isChangeableProperty($method) + { + $name = lcfirst(str_replace('set', '', $method)); + return in_array($name, $this->allowedProperties) ? true : false; + } + /** * Set default properties * @param [type] $custom [description] diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index fc2af498d..8ad8bd901 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -334,7 +334,7 @@ protected function _setAttribute($setter, $params) $key = lcfirst(str_replace('set', '', $setter)); // If is an allowed property - if(in_array($key, $this->excel->allowedProperties)) + if($this->excel->isChangeableProperty($setter)) { // Set the properties call_user_func_array(array($this->excel->getProperties(), $setter), $params); @@ -437,8 +437,15 @@ protected function _reset() */ public function __call($method, $params) { + // If the dynamic call starts with "set" + if(starts_with($method, 'set') && $this->excel->isChangeableProperty($method)) + { + $this->_setAttribute($method, $params); + return $this; + } + // Call a php excel method - if(method_exists($this->excel, $method)) + elseif(method_exists($this->excel, $method)) { // Call the method from the excel object with the given params call_user_func_array(array($this->excel, $method), $params); @@ -453,13 +460,6 @@ public function __call($method, $params) return $this; } - // If the dynamic call starts with "with", add the var to the data array - elseif(starts_with($method, 'set')) - { - $this->_setAttribute($method, $params); - return $this; - } - throw new LaravelExcelException('[ERROR] Writer method ['. $method .'] does not exist.'); } } \ No newline at end of file From 08aeb828869f3d85ca478ec148462bc26888facb Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 12:57:24 +0000 Subject: [PATCH 0130/1332] Added extra unit tests --- composer.json | 21 +++++---- .../Excel/ExcelServiceProvider.php | 9 +++- src/config/config.php | 2 +- tests/TestCase.php | 43 ++++++++++++++++++ tests/TestConfig.php | 19 ++++++++ tests/TestServiceProvider.php | 34 ++++++++++++++ tests/Writers/ExcelWriterTest.php | 45 +++++++++++++++++++ 7 files changed, 163 insertions(+), 10 deletions(-) create mode 100644 tests/TestCase.php create mode 100644 tests/TestConfig.php create mode 100644 tests/TestServiceProvider.php create mode 100644 tests/Writers/ExcelWriterTest.php diff --git a/composer.json b/composer.json index 2667e4ae3..5560bd96a 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "maatwebsite/excel", - "description": "An eloquent way of importing and exporting CSV in Laravel 4 with the power of PHPExcel", + "description": "An eloquent way of importing and exporting Excel and CSV in Laravel 4 with the power of PHPExcel", "license": "LGPL", "keywords": ["laravel", "phpexcel", "excel", "csv", "export", "import", "batch"], "authors": [ @@ -11,21 +11,26 @@ ], "require": { "php": ">=5.3.0", - "illuminate/support": "~4.0", - "illuminate/config": "~4.0", - "illuminate/filesystem": "~4.0", "phpoffice/phpexcel": "~1.8.0" }, "require-dev": { - "mockery/mockery": "~0.9.1", - "phpunit/phpunit": "~4.0" + "phpunit/phpunit": "~4.0", + "mockery/mockery": "~0.9", + "orchestra/testbench": "~2.1.1" }, "autoload": { "classmap": [ - "src/Maatwebsite/Excel" + "src/Maatwebsite/Excel", + "tests/TestCase.php" ], "psr-0": { "Maatwebsite\\Excel\\": "src/" } - } + }, + "repositories": [ + { + "type": "vcs", + "url": "git://github.com/orchestral/phpseclib.git" + } + ] } diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 9147792cd..ee7a8e27a 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -162,7 +162,14 @@ public function setLocale() */ public function provides() { - return array('excel'); + return array( + 'excel', + 'phpexcel', + 'excel.reader', + 'excel.readers.html', + 'excel.parsers.view', + 'excel.writer' + ); } } \ No newline at end of file diff --git a/src/config/config.php b/src/config/config.php index d0acf6c70..727d300fd 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -7,7 +7,7 @@ * Licensed under the LPGL. * * @package Laravel-4 PHPExcel - * @version 0.1.0 + * @version 1.* * @author Maatwebsite * @license LGPL * @copyright (c) 2013, Maatwebsite diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 000000000..85db54dc2 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,43 @@ +assertInstanceOf('Maatwebsite\Excel\Excel', $excel); + } + + /** + * Get the package service provider + * @return [type] [description] + */ + protected function getPackageProviders() + { + return array('Maatwebsite\Excel\ExcelServiceProvider'); + } + + /** + * Get the path for this package + * + * @return string + */ + protected function getPackagePath() + { + return realpath(implode(DIRECTORY_SEPARATOR, array( + __DIR__, + '..', + 'src', + 'Maatwebsite', + 'Excel' + ))); + } + +} \ No newline at end of file diff --git a/tests/TestConfig.php b/tests/TestConfig.php new file mode 100644 index 000000000..c09782905 --- /dev/null +++ b/tests/TestConfig.php @@ -0,0 +1,19 @@ +assertEquals(Config::get('excel::creator'), 'Maatwebsite'); + } + +} \ No newline at end of file diff --git a/tests/TestServiceProvider.php b/tests/TestServiceProvider.php new file mode 100644 index 000000000..7918a33bc --- /dev/null +++ b/tests/TestServiceProvider.php @@ -0,0 +1,34 @@ +assertCount(6, $provider->provides()); + + $this->assertContains('excel', $provider->provides()); + $this->assertContains('phpexcel', $provider->provides()); + $this->assertContains('excel.reader', $provider->provides()); + $this->assertContains('excel.readers.html', $provider->provides()); + $this->assertContains('excel.parsers.view', $provider->provides()); + $this->assertContains('excel.writer', $provider->provides()); + } +} \ No newline at end of file diff --git a/tests/Writers/ExcelWriterTest.php b/tests/Writers/ExcelWriterTest.php new file mode 100644 index 000000000..5f35ef5cd --- /dev/null +++ b/tests/Writers/ExcelWriterTest.php @@ -0,0 +1,45 @@ +excel = App::make('phpexcel'); + + // Set writer class + $this->writer = App::make('excel.writer'); + $this->writer->injectExcel($this->excel); + + } + + /** + * Test setCreator() + * @return [type] [description] + */ + public function testSetCreator() + { + $creatorSet = $this->writer->setCreator('Maatwebsite'); + $this->assertEquals($this->writer, $creatorSet); + } + + /** + * Test setTitle() + * @return [type] [description] + */ + public function testSetTitle() + { + $titleSet = $this->writer->setTitle('Workbook Title'); + $this->assertEquals($this->writer, $titleSet); + } + +} \ No newline at end of file From db2ed2a883dbc19cac78647484fce8282fad668a Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 12:58:49 +0000 Subject: [PATCH 0131/1332] Changelog update for v1.0.7 --- README.md | 2 +- docs/changelog/version-1.md | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7404e4261..64e0a3a6c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.6 +## Laravel Excel v1.0.7 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 8bde7ff1f..f02034c1c 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,10 @@ # Version 1 +### 1.0.7 + +- Set workbook properties fix +- Extra units tests + ### 1.0.6 - BatchReader fix From a3a675a86068f7def6d84e8dac5f19cb78a4dfc9 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 20:35:15 +0000 Subject: [PATCH 0132/1332] Further development of cell manipulator --- .../Excel/Classes/LaravelExcelWorksheet.php | 23 +++- src/Maatwebsite/Excel/Writers/CellWriter.php | 124 ++++++++++++++++-- 2 files changed, 136 insertions(+), 11 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 0472954e8..ff03bfa61 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -126,7 +126,26 @@ public function setDefaultPageSetup() } /** - * Init the cells + * Manipulate a single cell + * @param [type] $cell [description] + * @param boolean $callback [description] + * @return [type] [description] + */ + public function cell($cell, $callback = false) + { + // If a callback is given, handle it with the cell writer + if($callback instanceof Closure) + return $this->cells($cell, $callback); + + // Else if the 2nd param was set, we will use it as a cell value + if($callback) + $this->sheet->setCellValue($cell, $callback); + + return $this; + } + + /** + * Manipulate a cell or a range of cells * @return [type] [description] */ public function cells($cells, $callback = false) @@ -138,7 +157,7 @@ public function cells($cells, $callback = false) if($callback instanceof Closure) call_user_func($callback, $cells); - return $cells; + return $this; } /** diff --git a/src/Maatwebsite/Excel/Writers/CellWriter.php b/src/Maatwebsite/Excel/Writers/CellWriter.php index f8e320f84..785a1b70a 100644 --- a/src/Maatwebsite/Excel/Writers/CellWriter.php +++ b/src/Maatwebsite/Excel/Writers/CellWriter.php @@ -38,6 +38,21 @@ public function __construct($cells, LaravelExcelWorksheet $sheet) $this->sheet = $sheet; } + /** + * Set cell value + * @param [type] $value [description] + */ + public function setValue($value) + { + // Only set cell value for single cells + if(!str_contains($this->cells, ':')) + { + $this->sheet->setCellValue($this->cells, $value); + } + + return $this; + } + /** * Set the background * @param [type] $color [description] @@ -46,8 +61,7 @@ public function __construct($cells, LaravelExcelWorksheet $sheet) */ public function setBackground($color, $type = 'solid', $colorType = 'rgb') { - $this->setStyle('fill', $color, $type, $colorType); - return $this; + return $this->setColorStyle('fill', $color, $type, $colorType); } /** @@ -57,32 +71,124 @@ public function setBackground($color, $type = 'solid', $colorType = 'rgb') */ public function setFontColor($color, $colorType = 'rgb') { - $this->setStyle('font', $color, false, $colorType); - return $this; + return $this->setColorStyle('font', $color, false, $colorType); + } + + /** + * Set the font + * @param [type] $right [description] + */ + public function setFont($styles) + { + return $this->setStyle('font', $styles); + } + + /** + * Set font family + * @param [type] $family [description] + */ + public function setFontFamily($family) + { + return $this->setStyle('font', array( + 'name' => $family + )); + } + + /** + * Set font size + */ + public function setFontSize($size) + { + return $this->setStyle('font', array( + 'size' => $size + )); + } + + /** + * Set border + * @param [type] $top [description] + * @param boolean $right [description] + * @param boolean $bottom [description] + * @param boolean $left [description] + */ + public function setBorder($top = 'none', $right = 'none', $bottom = 'none', $left = 'none') + { + // Set the border styles + $styles = is_array($top) ? $top : array( + 'borders' => array( + 'top' => array( + 'style' => $top + ), + 'left' => array( + 'style' => $left, + ), + 'right' => array( + 'style' => $right, + ), + 'bottom' => array( + 'style' => $bottom, + ) + ) + ); + + return $this->setStyle('borders', $styles); } /** - * Set the style + * Set the alignment + * @param [type] $alignment [description] + */ + public function setAlignment($alignment) + { + return $this->setStyle('alignment', array( + 'horizontal' => $alignment + )); + } + + /** + * Set vertical alignment + * @param [type] $alignment [description] + */ + public function setValignment($alignment) + { + return $this->setStyle('alignment', array( + 'vertical' => $alignment + )); + } + + /** + * Set the color style * @param [type] $style [description] * @param [type] $color [description] * @param boolean $type [description] * @param string $colorType [description] */ - protected function setStyle($styleType, $color, $type = false, $colorType = 'rgb') + protected function setColorStyle($styleType, $color, $type = false, $colorType = 'rgb') { - // Get the cell style - $style = $this->getCellStyle(); - // Set the styles $styles = is_array($color) ? $color : array( 'type' => $type, 'color' => array($colorType => str_replace('#', '', $color)) ); + return $this->setStyle($styleType, $styles); + } + + /** + * Set style + * @param [type] $styles [description] + */ + protected function setStyle($styleType, $styles) + { + // Get the cell style + $style = $this->getCellStyle(); + // Apply style from array $style->applyFromArray(array( $styleType => $styles )); + + return $this; } /** From 3e2c0ef2807887ba2a635f60021c3cb0db939668 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 20:35:32 +0000 Subject: [PATCH 0133/1332] Start of row manipulator --- .../Excel/Classes/LaravelExcelWorksheet.php | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index ff03bfa61..7e289d00b 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -125,6 +125,42 @@ public function setDefaultPageSetup() } } + /** + * Manipulate a single row + * @param [type] $rowNumber [description] + * @param boolean $callback [description] + * @return [type] [description] + */ + public function row($rowNumber, $callback = false) + { + // If a callback is given, handle it with the cell writer + //if($callback instanceof Closure) + //return $this->rows($rowNumber, $callback); + + // Else if the 2nd param was set, we will use it as a cell value + if(is_array($callback)) + { + // Interpret the callback as cell values + $values = $callback; + + // Set start column + $column = 'A'; + + foreach($values as $rowValue) + { + // Set cell coordinate + $cell = $column . $rowNumber; + + // Set the cell value + $this->setCellValue($cell, $rowValue); + $column++; + } + + } + + return $this; + } + /** * Manipulate a single cell * @param [type] $cell [description] From 3e131e509aead944351e1b988397306b529833b7 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 22:38:12 +0000 Subject: [PATCH 0134/1332] More Writer Tests --- src/Maatwebsite/Excel/Classes/PHPExcel.php | 14 +- src/Maatwebsite/Excel/Parsers/ViewParser.php | 29 +++- .../Excel/Writers/LaravelExcelWriter.php | 61 ++++++++- tests/Writers/ExcelWriterTest.php | 124 ++++++++++++++++-- 4 files changed, 209 insertions(+), 19 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index eb5c15df2..be0a7cfc6 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -24,7 +24,6 @@ class PHPExcel extends PHPOffice_PHPExcel public $allowedProperties = array( 'creator', 'lastModifiedBy', - 'title', 'description', 'subject', 'keywords', @@ -60,7 +59,7 @@ public function createSheet($iSheetIndex = NULL, $title = false) public function isChangeableProperty($method) { $name = lcfirst(str_replace('set', '', $method)); - return in_array($name, $this->allowedProperties) ? true : false; + return in_array($name, $this->getAllowedProperties()) ? true : false; } /** @@ -73,7 +72,7 @@ public function setDefaultProperties($custom) $properties = $this->getProperties(); // Get fillable properties - foreach($this->allowedProperties as $prop) + foreach($this->getAllowedProperties() as $prop) { // Get the method $method = 'set' . ucfirst($prop); @@ -86,4 +85,13 @@ public function setDefaultProperties($custom) } } + /** + * Return all allowed properties + * @return [type] [description] + */ + public function getAllowedProperties() + { + return $this->allowedProperties; + } + } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Parsers/ViewParser.php b/src/Maatwebsite/Excel/Parsers/ViewParser.php index 1b1e5de91..70b4b6427 100644 --- a/src/Maatwebsite/Excel/Parsers/ViewParser.php +++ b/src/Maatwebsite/Excel/Parsers/ViewParser.php @@ -50,7 +50,7 @@ public function __construct(Html $reader) */ public function parse($sheet) { - $html = View::make($this->view, $this->data, $this->mergeData)->render(); + $html = View::make($this->getView(), $this->getData(), $this->getMergeData())->render(); return $this->_loadHTML($sheet, $html); } @@ -65,6 +65,33 @@ protected function _loadHTML($sheet, $html) return $this->reader->load($html, true, $sheet); } + /** + * Get the view + * @return [type] [description] + */ + public function getView() + { + return $this->view; + } + + /** + * Get data + * @return [type] [description] + */ + public function getData() + { + return $this->data; + } + + /** + * Get merge data + * @return [type] [description] + */ + public function getMergeData() + { + return $this->mergeData; + } + /** * Set the view * @param [type] $view [description] diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 8ad8bd901..7d479db09 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -45,6 +45,12 @@ class LaravelExcelWriter { */ public $writer; + /** + * Excel sheet + * @var [type] + */ + protected $sheet; + /** * Parser * @var [type] @@ -104,18 +110,27 @@ public function injectExcel($excel) public function setTitle($title) { $this->title = $title; + $this->getProperties()->setTitle($title); return $this; } + /** + * Get the title + * @return [type] [description] + */ + public function getTitle() + { + return $this->title; + } + /** * Share a view with all sheets * @return [type] [description] */ public function shareView($view, $data = array(), $mergeData = array()) { - // Init the parser - if(!$this->parser) - $this->parser = app('excel.parsers.view'); + // Get the parser + $this->getParser(); // Set the view inside the parser $this->parser->setView($view); @@ -187,6 +202,7 @@ public function with(Array $array) { // Add the vars $this->fromArray($array); + return $this; } /** @@ -323,6 +339,37 @@ protected function _render() $this->rendered = true; } + /** + * Get the view parser + * @return [type] [description] + */ + public function getExcel() + { + return $this->excel; + } + + /** + * Get the view parser + * @return [type] [description] + */ + public function getParser() + { + // Init the parser + if(!$this->parser) + $this->parser = app('excel.parsers.view'); + + return $this->parser; + } + + /** + * Get the sheet + * @return [type] [description] + */ + public function getSheet() + { + return $this->sheet; + } + /** * Set attributes * @param [type] $setter [description] @@ -448,16 +495,16 @@ public function __call($method, $params) elseif(method_exists($this->excel, $method)) { // Call the method from the excel object with the given params - call_user_func_array(array($this->excel, $method), $params); - return $this; + $return = call_user_func_array(array($this->excel, $method), $params); + return $return ? $return : $this; } // Call a php excel sheet method elseif(method_exists($this->excel->getActiveSheet(), $method)) { // Call the method from the excel object with the given params - call_user_func_array(array($this->excel->getActiveSheet(), $method), $params); - return $this; + $return = call_user_func_array(array($this->excel->getActiveSheet(), $method), $params); + return $return ? $return : $this; } throw new LaravelExcelException('[ERROR] Writer method ['. $method .'] does not exist.'); diff --git a/tests/Writers/ExcelWriterTest.php b/tests/Writers/ExcelWriterTest.php index 5f35ef5cd..a9b81badd 100644 --- a/tests/Writers/ExcelWriterTest.php +++ b/tests/Writers/ExcelWriterTest.php @@ -19,27 +19,135 @@ public function setUp() // Set writer class $this->writer = App::make('excel.writer'); $this->writer->injectExcel($this->excel); + } + + /** + * Test setTitle() + * @return [type] [description] + */ + public function testSetTitle() + { + $title = 'Workbook Title'; + $titleSet = $this->writer->setTitle($title); + $this->assertEquals($this->writer, $titleSet); + // Test if title was really set + $this->assertEquals($this->writer->getTitle(), $title); + $this->assertEquals($this->writer->getProperties()->getTitle(), $title); } /** - * Test setCreator() + * Test the share view * @return [type] [description] */ - public function testSetCreator() + public function testShareView() { - $creatorSet = $this->writer->setCreator('Maatwebsite'); - $this->assertEquals($this->writer, $creatorSet); + // Set params + $view = 'excel'; + $data = array(); + $mergeData = array(); + + $viewShared = $this->writer->shareView($view, $data, $mergeData); + $this->assertEquals($this->writer, $viewShared); + + // Get the parser + $parser = $this->writer->getParser(); + + // Test if parse data was set + $this->assertEquals($parser->getView(), $view); + $this->assertEquals($parser->getData(), $data); + $this->assertEquals($parser->getMergeData(), $mergeData); } /** - * Test setTitle() + * Test basic sheet creation * @return [type] [description] */ - public function testSetTitle() + public function testSheet() { - $titleSet = $this->writer->setTitle('Workbook Title'); - $this->assertEquals($this->writer, $titleSet); + $title = 'Worksheet Title'; + $sheetCreated = $this->writer->sheet($title); + + $this->assertEquals($this->writer, $sheetCreated); + + // Test if title was really set + $this->assertEquals($this->writer->getSheet()->getTitle(), $title); + } + + /** + * Test sheet closure + * @return [type] [description] + */ + public function testSheetClosure() + { + $title = 'Worksheet Title'; + $closureTitle = 'Closure Title'; + + $this->writer->sheet($title, function($sheet) use($closureTitle) { + $sheet->setTitle($closureTitle); + }); + + // Test if title was really set + $this->assertEquals($this->writer->getSheet()->getTitle(), $closureTitle); + } + + /** + * Test multiple sheet creation + * @return [type] [description] + */ + public function testMultipleSheets() + { + // Set sheet titles + $sheets = array( + 'Worksheet 1 title', + 'Worksheet 2 title', + 'Worksheet 3 title' + ); + + // Create the sheets + foreach($sheets as $sheetTitle) + { + $this->writer->sheet($sheetTitle); + } + + // Count amount of sheets + $this->assertEquals(count($sheets), $this->writer->getSheetCount()); + + // Test if all sheet titles where set correctly + foreach($sheets as $sheetTitle) + { + $this->assertContains($sheetTitle, $this->writer->getSheetNames()); + } + } + + /** + * Test setting properties (creator, ...) + * @return [type] [description] + */ + public function testSetProperties() + { + // Get available properties + $properties = $this->excel->getAllowedProperties(); + + // Loop through them + foreach($properties as $prop) + { + // Set a random value + $originalValue = rand(); + + // Set needed set/get methods + $method = 'set' . ucfirst($prop); + $getMethod = 'get' . ucfirst($prop); + + // Set the property with the random value + call_user_func_array(array($this->writer, $method), array($originalValue)); + + // Get the property back + $returnedValue = call_user_func_array(array($this->writer->getProperties(), $getMethod), array()); + + // Check if the properties matches + $this->assertEquals($originalValue, $returnedValue, $prop . ' doesn\'t match'); + } } } \ No newline at end of file From 8a8cb11cde7f77f4f4074452c2418043a4b8b00c Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 23:23:59 +0000 Subject: [PATCH 0135/1332] Creating sheet fromModel() + auto generate table heading based on array indices --- .../Excel/Classes/LaravelExcelWorksheet.php | 83 ++++++++++++++++++- src/config/export.php | 11 +++ 2 files changed, 92 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 7e289d00b..0f1525cbc 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -3,6 +3,7 @@ use \Closure; use \Config; use \PHPExcel_Worksheet; +use Illuminate\Support\Collection; use Maatwebsite\Excel\Writers\CellWriter; use Maatwebsite\Excel\Exceptions\LaravelExcelException; @@ -283,6 +284,20 @@ public function with($key, $value = false) return $this; } + /** + * From array + * @param [type] $key [description] + * @return [type] [description] + */ + public function fromModel($source = NULL, $nullValue = NULL, $startCell = 'A1', $strictNullComparison = false) + { + // Add the vars + $this->_addVars($source); + + // create from array + return parent::fromArray($this->data, $nullValue, $startCell, $strictNullComparison); + } + /** * Add vars to the data array * @param [type] $key [description] @@ -291,10 +306,10 @@ public function with($key, $value = false) protected function _addVars($key, $value = false) { // Add array of data - if(is_array($key)) + if(is_array($key) || $key instanceof Collection) { // Set the data - $this->data = array_merge($this->data, $key); + $this->data = $this->addData($key); // Create excel from array without a view if(!$this->parser) @@ -312,6 +327,70 @@ protected function _addVars($key, $value = false) $this->parser->setData($this->data); } + /** + * Array + * @param [type] $array [description] + */ + protected function addData($array) + { + // If a parser was set + if($this->parser) + { + // Don't change anything + $data = $array; + } + else + { + // Transform model/collection to array + if($array instanceof Collection) + $array = $array->toArray(); + + // Get the firstRow + $firstRow = reset($array); + + // Check if the array has array values + if(count($firstRow) != count($firstRow, 1)) + { + // Loop through the data to remove arrays + $data = array(); + $r = 0; + foreach($array as $row) + { + $data[$r] = array(); + foreach($row as $key => $cell) + { + if(!is_array($cell)) + { + $data[$r][$key] = $cell; + } + } + $r++; + } + } + else + { + $data = $array; + } + + // Check if we should auto add the first row based on the indices + if(Config::get('excel::export.generate_heading_by_indices', false)) + { + // Get the first row + $firstRow = reset($data); + + // Get the array keys + $tableHeading = array_keys($firstRow); + + // Add table headings as first row + array_unshift($data, $tableHeading); + } + + } + + // return data + return array_merge($this->data, $data); + } + /** * Set attributes * @param [type] $key [description] diff --git a/src/config/export.php b/src/config/export.php index ba53be3af..cb625cde2 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -13,6 +13,17 @@ */ 'autosize' => true, + /* + |-------------------------------------------------------------------------- + | Auto generate table heading + |-------------------------------------------------------------------------- + | + | If set to true, the array indices (or model attribute names) + | will automatically be used as first row (table heading) + | + */ + 'generate_heading_by_indices' => true, + /* |-------------------------------------------------------------------------- | Store settings From 9770d5faefe115e475087efacde3291f4426bfe4 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 23 May 2014 23:31:22 +0000 Subject: [PATCH 0136/1332] Added option to disable auto table heading generation --- .../Excel/Classes/LaravelExcelWorksheet.php | 53 +++++++++++++++++-- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 0f1525cbc..2b30ed793 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -92,6 +92,12 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet */ public $wasAutoSized = false; + /** + * Auto generate table heading + * @var [type] + */ + protected $autoGenerateHeading = true; + /** * Create a new worksheet * @@ -277,8 +283,11 @@ public function parsed() * @param boolean $value [description] * @return [type] [description] */ - public function with($key, $value = false) + public function with($key, $value = false, $headingGeneration = true) { + // Set the heading generation setting + $this->setAutoHeadingGeneration($headingGeneration); + // Add the vars $this->_addVars($key, $value); return $this; @@ -289,13 +298,16 @@ public function with($key, $value = false) * @param [type] $key [description] * @return [type] [description] */ - public function fromModel($source = NULL, $nullValue = NULL, $startCell = 'A1', $strictNullComparison = false) + public function fromModel($source = NULL, $headingGeneration = true) { + // Set the heading generation setting + $this->setAutoHeadingGeneration($headingGeneration); + // Add the vars $this->_addVars($source); // create from array - return parent::fromArray($this->data, $nullValue, $startCell, $strictNullComparison); + return parent::fromArray($this->data); } /** @@ -373,7 +385,7 @@ protected function addData($array) } // Check if we should auto add the first row based on the indices - if(Config::get('excel::export.generate_heading_by_indices', false)) + if($this->generateHeadingByIndices()) { // Get the first row $firstRow = reset($data); @@ -391,6 +403,39 @@ protected function addData($array) return array_merge($this->data, $data); } + /** + * Set the auto heading generation setting + * @param [type] $boolean [description] + */ + public function setAutoHeadingGeneration($boolean) + { + $this->autoGenerateHeading = $boolean; + return $this; + } + + /** + * Disable the heading generation + * @param boolean $boolean [description] + * @return [type] [description] + */ + public function disableHeadingGeneration($boolean = false) + { + $this->setAutoHeadingGeneration($boolean); + return $this; + } + + /** + * Check if we should auto generate the table heading + * @return [type] [description] + */ + protected function generateHeadingByIndices() + { + if(!$this->autoGenerateHeading) + return false; + + return Config::get('excel::export.generate_heading_by_indices', false); + } + /** * Set attributes * @param [type] $key [description] From 9d3821913da4171a68bbca9fe59b0753e2e0ad19 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 24 May 2014 13:41:58 +0000 Subject: [PATCH 0137/1332] Parse HTML width and height attributes with loadView() --- .../Excel/Classes/LaravelExcelWorksheet.php | 10 +--- src/Maatwebsite/Excel/Readers/HtmlReader.php | 46 ++++++++++++++++++- .../Excel/Readers/LaravelExcelReader.php | 9 ++++ .../Excel/Writers/LaravelExcelWriter.php | 6 ++- 4 files changed, 60 insertions(+), 11 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 2b30ed793..267769839 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -80,12 +80,6 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet 'fontBold' ); - /** - * Dynamically autosized - * @var boolean - */ - public $autoSize = false; - /** * Check if the file was autosized * @var boolean @@ -601,7 +595,7 @@ public function setWidth($column, $value = false) * @param [type] $row [description] * @param boolean $value [description] */ - public function setHeight($row, $valu§e = false) + public function setHeight($row, $value = false) { // if is array of columns if(is_array($row)) @@ -698,7 +692,7 @@ public function setAutoSize($columns = false) */ public function getAutosize() { - if($this->autoSize) + if(isset($this->autoSize)) return $this->autoSize; return Config::get('excel::export.autosize', true); diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index aa39ae5b0..7c70121d2 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -237,7 +237,16 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Inline css styles case 'style': $this->parseInlineStyles($sheet, $column, $row, $attribute->value); - break; + break; + + // Colspan + case 'width': + $this->parseWidth($sheet, $column, $row, $attribute->value); + break; + + case 'height': + $this->parseHeight($sheet, $column, $row, $attribute->value); + break; // Colspan case 'colspan': @@ -720,6 +729,32 @@ protected function styleById($sheet, $column, $row, $class) } } + /** + * Set column width + * @param [type] $sheet [description] + * @param [type] $column [description] + * @param [type] $row [description] + * @param [type] $width [description] + * @return [type] [description] + */ + protected function parseWidth($sheet, $column, $row, $width) + { + $sheet->setWidth($column, $width); + } + + /** + * Set row height + * @param [type] $sheet [description] + * @param [type] $column [description] + * @param [type] $row [description] + * @param [type] $height [description] + * @return [type] [description] + */ + protected function parseHeight($sheet, $column, $row, $height) + { + $sheet->setHeight($row, $height); + } + /** * Parse colspans * @param [type] $sheet [description] @@ -898,6 +933,15 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) $cells = $sheet->getStyle($column.$row); switch($name) { + // Cell width + case 'width': + $this->parseWidth($sheet, $column, $row, $value); + break; + + // Row height + case 'height': + $this->parseHeight($sheet, $column, $row, $value); + break; // BACKGROUND case 'background': diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 826cb1eab..1562ca5f4 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -703,6 +703,15 @@ protected function _reset() $this->excel->disconnectWorksheets(); } + /** + * Get excel object + * @return [type] [description] + */ + public function getExcel() + { + return $this->excel; + } + /** * Dynamically call methods * @param [type] $method [description] diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 7d479db09..c83a237eb 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -97,10 +97,12 @@ public function __construct(Response $response, FileSystem $filesystem) * @param [type] $excel [description] * @return [type] [description] */ - public function injectExcel($excel) + public function injectExcel($excel, $reset = true) { $this->excel = $excel; - $this->_reset(); + + if($reset) + $this->_reset(); } /** From 6f2a6307652d97c0490faaff3bef1becfd6b8554 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 24 May 2014 14:11:01 +0000 Subject: [PATCH 0138/1332] Insert images from view with loadView() --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 46 ++++++++++++++++++-- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 7c70121d2..62923e690 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -15,6 +15,7 @@ use \PHPExcel_Style_Alignment; use Maatwebsite\Excel\Parsers\CssParser; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; +use \PHPExcel_Worksheet_MemoryDrawing; /** * @@ -277,10 +278,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & case 'id': $this->styleById($sheet, $column, $row, $attribute->value); break; - } - - } // nodeName @@ -515,6 +513,10 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & $this->_processDomElement($child,$sheet,$row,$column,$cellContent); break; + case 'img': + $this->insertImageBySrc($sheet, $column, $row, $child); + break; + // Table rows case 'tr' : @@ -729,6 +731,44 @@ protected function styleById($sheet, $column, $row, $class) } } + /** + * Insert a image inside the sheet + * @param [type] $sheet [description] + * @param [type] $column [description] + * @param [type] $row [description] + * @param [type] $src [description] + * @return [type] [description] + */ + protected function insertImageBySrc($sheet, $column, $row, $attributes) + { + // Get attributes + $src = $attributes->getAttribute('src'); + $width = $attributes->getAttribute('width'); + $height = $attributes->getAttribute('height'); + $alt = $attributes->getAttribute('alt'); + + // Create image from src value + $image = imagecreatefrompng($src); + + // init drawing + $drawing = new PHPExcel_Worksheet_MemoryDrawing(); + + // Set image + $drawing->setImageResource($image); + $drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG); + $drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT); + + // Set name + $drawing->setName($alt); + + // Set location information + $drawing->setWorksheet($sheet); + $drawing->setCoordinates($column . $row); + + // Set height and width + $drawing->setWidthAndHeight($width, $height); + } + /** * Set column width * @param [type] $sheet [description] From b896c18c9d7d050be3ec7eb483ee0119ff9255e5 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 24 May 2014 14:31:06 +0000 Subject: [PATCH 0139/1332] Autosize cell based on image --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 30 ++++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 62923e690..18b8af57e 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -15,7 +15,7 @@ use \PHPExcel_Style_Alignment; use Maatwebsite\Excel\Parsers\CssParser; use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; -use \PHPExcel_Worksheet_MemoryDrawing; +use \PHPExcel_Worksheet_Drawing; /** * @@ -743,30 +743,30 @@ protected function insertImageBySrc($sheet, $column, $row, $attributes) { // Get attributes $src = $attributes->getAttribute('src'); - $width = $attributes->getAttribute('width'); - $height = $attributes->getAttribute('height'); + $width = (float) $attributes->getAttribute('width'); + $height = (float) $attributes->getAttribute('height'); $alt = $attributes->getAttribute('alt'); - // Create image from src value - $image = imagecreatefrompng($src); - // init drawing - $drawing = new PHPExcel_Worksheet_MemoryDrawing(); + $drawing = new PHPExcel_Worksheet_Drawing(); // Set image - $drawing->setImageResource($image); - $drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG); - $drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT); - - // Set name + $drawing->setPath($src); $drawing->setName($alt); - - // Set location information $drawing->setWorksheet($sheet); $drawing->setCoordinates($column . $row); + $drawing->setResizeProportional(); // Set height and width - $drawing->setWidthAndHeight($width, $height); + if($width > 0) + $drawing->setWidth($width); + + if($height > 0) + $drawing->setHeight($height); + + // Set cell width based on image + $this->parseWidth($sheet, $column, $row, $drawing->getWidth()); + $this->parseHeight($sheet, $column, $row, $drawing->getHeight()); } /** From 44f297f6ba6033a45e1836db8848be42ba925656 Mon Sep 17 00:00:00 2001 From: "Barry vd. Heuvel" Date: Tue, 27 May 2014 13:54:52 +0200 Subject: [PATCH 0140/1332] Update some phpdocs Just the start.. I think the default for empty parameters is usually `null` instead of `false`. `str` and `closure` aren't the official types, `string` and `callback` are. When importing classes with `use`, the first `\` isn't needed. --- src/Maatwebsite/Excel/Excel.php | 55 ++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index cb292421e..a66994f85 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -1,7 +1,7 @@ excel->setDefaultProperties(array( @@ -87,12 +86,13 @@ public function create($title, $callback = false) * * Load an existing file * - * @param str $file The file we want to load - * @param closure A callback + * @param string $file The file we want to load + * @param callback|null $callback + * @param string|null $encoding * @return $this * */ - public function load($file, $callback = false, $encoding = false) + public function load($file, $callback = null, $encoding = null) { // Inject excel object $this->reader->injectExcel($this->excel); @@ -113,8 +113,8 @@ public function load($file, $callback = false, $encoding = false) /** * Set select sheets - * @param [type] $sheets [description] - * @return [type] [description] + * @param $sheets + * @return $this */ public function selectSheets($sheets) { @@ -124,7 +124,9 @@ public function selectSheets($sheets) /** * Batch import - * @return [type] [description] + * @param $files + * @param callback $callback + * @return $this */ public function batch($files, Closure $callback) { @@ -134,7 +136,10 @@ public function batch($files, Closure $callback) /** * Create a new file and share a view - * @return [type] [description] + * @param string $view + * @param array $data + * @param array $mergeData + * @return LaravelExcelWriter */ public function shareView($view, $data = array(), $mergeData = array()) { @@ -143,7 +148,10 @@ public function shareView($view, $data = array(), $mergeData = array()) /** * Create a new file and load a view - * @return [type] [description] + * @param string $view + * @param array $data + * @param array $mergeData + * @return LaravelExcelWriter */ public function loadView($view, $data = array(), $mergeData = array()) { @@ -152,9 +160,6 @@ public function loadView($view, $data = array(), $mergeData = array()) /** * Dynamically call methods - * @param [type] $method [description] - * @param [type] $params [description] - * @return [type] [description] */ public function __call($method, $params) { @@ -168,4 +173,4 @@ public function __call($method, $params) throw new LaravelExcelException('Laravel Excel method ['. $method .'] does not exist'); } -} \ No newline at end of file +} From 92eb514604b54b79b9a14142b31d11866b90ac97 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 27 May 2014 23:54:23 +0200 Subject: [PATCH 0141/1332] Own file format identifier, possibly fixes issue #130 --- .../Excel/Readers/LaravelExcelReader.php | 56 ++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 1562ca5f4..035d9da88 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -620,10 +620,64 @@ public function getLimit() */ protected function _setFormat() { - $this->format = PHPExcel_IOFactory::identify($this->file); + $this->format = $this->identify($this->file); return $this; } + /** + * Identify file format + * @return [type] [description] + */ + protected function identify($file) + { + switch ($this->getExtension($file)) { + case 'xlsx': + case 'xlsm': + case 'xltx': + case 'xltm': + return 'Excel2007'; + break; + case 'xls': + case 'xlt': + return 'Excel5'; + break; + case 'ods': + case 'ots': + return 'OOCalc'; + break; + case 'slk': + return 'SYLK'; + break; + case 'xml': + return 'Excel2003XML'; + break; + case 'gnumeric': + return 'Gnumeric'; + break; + case 'htm': + case 'html': + return 'HTML'; + break; + case 'csv': + case 'txt': + return 'CSV'; + break; + } + + throw new LaravelExcelException('[ERROR] Reader could not identify file format for file ['. $file .'].'); + + } + + /** + * Get the file extension + * @param [type] $file [description] + * @return [type] [description] + */ + protected function getExtension($file) + { + return strtolower($this->filesystem->extension($file)); + } + /** * Parse the file * @return [type] [description] From d0e42f22ad670071b00013bfb29c288d63385dca Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 28 May 2014 01:10:01 +0200 Subject: [PATCH 0142/1332] Auto table heading generator fix --- .../Excel/Classes/LaravelExcelWorksheet.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 267769839..c87dc7f23 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -384,11 +384,14 @@ protected function addData($array) // Get the first row $firstRow = reset($data); - // Get the array keys - $tableHeading = array_keys($firstRow); + if(is_array($firstRow)) + { + // Get the array keys + $tableHeading = array_keys($firstRow); - // Add table headings as first row - array_unshift($data, $tableHeading); + // Add table headings as first row + array_unshift($data, $tableHeading); + } } } From d38ef737e3f19619b1aabda8df4ea3cdfcc28211 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 28 May 2014 22:08:40 +0200 Subject: [PATCH 0143/1332] Enhanced format identifier for reading and writing --- .../Excel/Classes/FormatIdentifier.php | 263 ++++++++++++++++++ .../Excel/ExcelServiceProvider.php | 40 ++- .../Excel/Readers/LaravelExcelReader.php | 72 +---- .../Excel/Writers/LaravelExcelWriter.php | 38 +-- 4 files changed, 312 insertions(+), 101 deletions(-) create mode 100644 src/Maatwebsite/Excel/Classes/FormatIdentifier.php diff --git a/src/Maatwebsite/Excel/Classes/FormatIdentifier.php b/src/Maatwebsite/Excel/Classes/FormatIdentifier.php new file mode 100644 index 000000000..f364f7e5e --- /dev/null +++ b/src/Maatwebsite/Excel/Classes/FormatIdentifier.php @@ -0,0 +1,263 @@ +filesystem = $filesystem; + } + + /** + * Get the file format by file + * @return string $format + */ + public function getFormatByFile($file) + { + // get the file extension + $ext = $this->getExtension($file); + + // get the file format + $format = $this->getFormatByExtension($ext); + + // Check if the file can be read + if($this->canRead($format, $file)) + return $format; + + // Do a last try to init the file with all available readers + return $this->lastResort($file, $format); + } + + /** + * Identify file format + * @return string $format + */ + public function getFormatByExtension($ext) + { + switch($ext) { + + /* + |-------------------------------------------------------------------------- + | Excel 2007 + |-------------------------------------------------------------------------- + */ + case 'xlsx': + case 'xlsm': + case 'xltx': + case 'xltm': + return 'Excel2007'; + break; + + /* + |-------------------------------------------------------------------------- + | Excel5 + |-------------------------------------------------------------------------- + */ + case 'xls': + case 'xlt': + return 'Excel5'; + break; + + /* + |-------------------------------------------------------------------------- + | OOCalc + |-------------------------------------------------------------------------- + */ + case 'ods': + case 'ots': + return 'OOCalc'; + break; + + /* + |-------------------------------------------------------------------------- + | SYLK + |-------------------------------------------------------------------------- + */ + case 'slk': + return 'SYLK'; + break; + + /* + |-------------------------------------------------------------------------- + | Excel2003XML + |-------------------------------------------------------------------------- + */ + case 'xml': + return 'Excel2003XML'; + break; + + /* + |-------------------------------------------------------------------------- + | Gnumeric + |-------------------------------------------------------------------------- + */ + case 'gnumeric': + return 'Gnumeric'; + break; + + /* + |-------------------------------------------------------------------------- + | HTML + |-------------------------------------------------------------------------- + */ + case 'htm': + case 'html': + return 'HTML'; + break; + + /* + |-------------------------------------------------------------------------- + | CSV + |-------------------------------------------------------------------------- + */ + case 'csv': + case 'txt': + return 'CSV'; + break; + + /* + |-------------------------------------------------------------------------- + | PDF + |-------------------------------------------------------------------------- + */ + // case 'pdf': + // return 'PDF'; + // break; + } + } + + /** + * Get the content type by file format + * @param string $format [description] + * @return string $contentType + */ + public function getContentTypeByFormat($format) + { + switch($format) + { + + /* + |-------------------------------------------------------------------------- + | Excel 2007 + |-------------------------------------------------------------------------- + */ + case 'Excel2007': + return'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'; + break; + + /* + |-------------------------------------------------------------------------- + | Excel5 + |-------------------------------------------------------------------------- + */ + case 'Excel5': + return'application/vnd.ms-excel; charset=UTF-8'; + break; + + /* + |-------------------------------------------------------------------------- + | HTML + |-------------------------------------------------------------------------- + */ + case 'HTML': + return 'HTML'; + break; + + /* + |-------------------------------------------------------------------------- + | CSV + |-------------------------------------------------------------------------- + */ + case 'CSV': + return'application/csv; charset=UTF-8'; + break; + + /* + |-------------------------------------------------------------------------- + | PDF + |-------------------------------------------------------------------------- + */ + // case 'PDF': + // return'application/pdf; charset=UTF-8'; + // break; + } + } + + /** + * Try every reader we have + * @return string $format + */ + protected function lastResort($file, $wrongFormat = false) + { + // Loop through all available formats + foreach ($this->formats as $format) + { + // Check if the file could be read + if($wrongFormat != $format && $this->canRead($format, $file)) + return $format; + } + + // Give up searching and throw an exception + throw new LaravelExcelException('[ERROR] Reader could not identify file format for file ['. $file .'] with extension [' . $ext . ']'); + } + + /** + * Check if we can read the file + * @return boolean + */ + protected function canRead($format, $file) + { + if($format) + { + $reader = $this->initReader($format); + return $reader && $reader->canRead($file); + } + + return false; + } + + /** + * Init the reader based on the format + * @param string $format + * @return Reader + */ + protected function initReader($format) + { + return PHPExcel_IOFactory::createReader($format); + } + + /** + * Get the file extension + * @param string $file + * @return string + */ + protected function getExtension($file) + { + return strtolower($this->filesystem->extension($file)); + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index ee7a8e27a..a2c2c3f67 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -1,15 +1,16 @@ bindClasses(); $this->bindReaders(); $this->bindParsers(); $this->bindPHPExcelClass(); @@ -58,11 +60,10 @@ public function register() /** * Bind PHPExcel classes - * @return [type] [description] + * @return void */ protected function bindPHPExcelClass() { - // Set object $me = $this; @@ -82,14 +83,14 @@ protected function bindPHPExcelClass() /** * Bind writers - * @return [type] [description] + * @return void */ protected function bindReaders() { // Bind the laravel excel reader $this->app['excel.reader'] = $this->app->share(function($app) { - return new LaravelExcelReader($app['files']); + return new LaravelExcelReader($app['files'], $app['excel.identifier']); }); // Bind the html reader class @@ -101,7 +102,7 @@ protected function bindReaders() /** * Bind writers - * @return [type] [description] + * @return void */ protected function bindParsers() { @@ -114,20 +115,20 @@ protected function bindParsers() /** * Bind writers - * @return [type] [description] + * @return void */ protected function bindWriters() { // Bind the excel writer $this->app['excel.writer'] = $this->app->share(function($app) { - return new LaravelExcelWriter($app->make('Response'), $app['files']); + return new LaravelExcelWriter($app->make('Response'), $app['files'], $app['excel.identifier']); }); } /** * Bind Excel class - * @return [type] [description] + * @return void */ protected function bindExcel() { @@ -139,7 +140,20 @@ protected function bindExcel() } /** - * Set the cache settings + * Bind other classes + * @return [type] [description] + */ + protected function bindClasses() + { + // Bind the format identifier + $this->app['excel.identifier'] = $this->app->share(function($app) { + return new FormatIdentifier($app['files']); + }); + } + + /** + * Set cache settings + * @return Maatwebsite\Excel\Classes\Cache */ public function setCacheSettings() { diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 035d9da88..ef7fbb260 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -1,10 +1,11 @@ filesystem = $filesystem; + $this->identifier = $identifier; } /** @@ -620,64 +622,10 @@ public function getLimit() */ protected function _setFormat() { - $this->format = $this->identify($this->file); + $this->format = $this->identifier->getFormatByFile($this->file); return $this; } - /** - * Identify file format - * @return [type] [description] - */ - protected function identify($file) - { - switch ($this->getExtension($file)) { - case 'xlsx': - case 'xlsm': - case 'xltx': - case 'xltm': - return 'Excel2007'; - break; - case 'xls': - case 'xlt': - return 'Excel5'; - break; - case 'ods': - case 'ots': - return 'OOCalc'; - break; - case 'slk': - return 'SYLK'; - break; - case 'xml': - return 'Excel2003XML'; - break; - case 'gnumeric': - return 'Gnumeric'; - break; - case 'htm': - case 'html': - return 'HTML'; - break; - case 'csv': - case 'txt': - return 'CSV'; - break; - } - - throw new LaravelExcelException('[ERROR] Reader could not identify file format for file ['. $file .'].'); - - } - - /** - * Get the file extension - * @param [type] $file [description] - * @return [type] [description] - */ - protected function getExtension($file) - { - return strtolower($this->filesystem->extension($file)); - } - /** * Parse the file * @return [type] [description] diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index c83a237eb..263fd5bd3 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -1,10 +1,11 @@ response = $response; $this->filesystem = $filesystem; + $this->identifier = $identifier; } /** @@ -395,30 +397,14 @@ protected function _setAttribute($setter, $params) */ protected function _setFormat() { + // Get extension $this->ext = strtolower($this->ext); - switch($this->ext) - { - case 'xls': - $this->format = 'Excel5'; - $this->contentType = 'application/vnd.ms-excel; charset=UTF-8'; - break; - - case 'xlsx': - $this->format = 'Excel2007'; - $this->contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'; - break; - - case 'csv': - $this->format = 'CSV'; - $this->contentType = 'application/csv; charset=UTF-8'; - break; - - default: - $this->format = 'Excel5'; - $this->contentType = 'application/vnd.ms-excel; charset=UTF-8'; - break; - } + // get the file format + $this->format = $this->identifier->getFormatByExtension($this->ext); + + // Get content type + $this->contentType = $this->identifier->getContentTypeByFormat($this->format); } /** From 3745346e4982728e5bdc93a249edd568c7b37086 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 27 May 2014 23:54:23 +0200 Subject: [PATCH 0144/1332] Own file format identifier, possibly fixes issue #130 --- .../Excel/Readers/LaravelExcelReader.php | 56 ++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 7d51873ac..b00e49a22 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -578,10 +578,64 @@ public function needsDateFormatting() */ protected function _setFormat() { - $this->format = PHPExcel_IOFactory::identify($this->file); + $this->format = $this->identify($this->file); return $this; } + /** + * Identify file format + * @return [type] [description] + */ + protected function identify($file) + { + switch ($this->getExtension($file)) { + case 'xlsx': + case 'xlsm': + case 'xltx': + case 'xltm': + return 'Excel2007'; + break; + case 'xls': + case 'xlt': + return 'Excel5'; + break; + case 'ods': + case 'ots': + return 'OOCalc'; + break; + case 'slk': + return 'SYLK'; + break; + case 'xml': + return 'Excel2003XML'; + break; + case 'gnumeric': + return 'Gnumeric'; + break; + case 'htm': + case 'html': + return 'HTML'; + break; + case 'csv': + case 'txt': + return 'CSV'; + break; + } + + throw new LaravelExcelException('[ERROR] Reader could not identify file format for file ['. $file .'].'); + + } + + /** + * Get the file extension + * @param [type] $file [description] + * @return [type] [description] + */ + protected function getExtension($file) + { + return strtolower($this->filesystem->extension($file)); + } + /** * Parse the file * @return [type] [description] From 3cc02c5d68739ad17e8149b9b6346b7ab7187b04 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 28 May 2014 22:08:40 +0200 Subject: [PATCH 0145/1332] Enhanced format identifier for reading and writing --- .../Excel/Classes/FormatIdentifier.php | 263 ++++++++++++++++++ .../Excel/ExcelServiceProvider.php | 40 ++- .../Excel/Readers/LaravelExcelReader.php | 72 +---- .../Excel/Writers/LaravelExcelWriter.php | 38 +-- 4 files changed, 312 insertions(+), 101 deletions(-) create mode 100644 src/Maatwebsite/Excel/Classes/FormatIdentifier.php diff --git a/src/Maatwebsite/Excel/Classes/FormatIdentifier.php b/src/Maatwebsite/Excel/Classes/FormatIdentifier.php new file mode 100644 index 000000000..f364f7e5e --- /dev/null +++ b/src/Maatwebsite/Excel/Classes/FormatIdentifier.php @@ -0,0 +1,263 @@ +filesystem = $filesystem; + } + + /** + * Get the file format by file + * @return string $format + */ + public function getFormatByFile($file) + { + // get the file extension + $ext = $this->getExtension($file); + + // get the file format + $format = $this->getFormatByExtension($ext); + + // Check if the file can be read + if($this->canRead($format, $file)) + return $format; + + // Do a last try to init the file with all available readers + return $this->lastResort($file, $format); + } + + /** + * Identify file format + * @return string $format + */ + public function getFormatByExtension($ext) + { + switch($ext) { + + /* + |-------------------------------------------------------------------------- + | Excel 2007 + |-------------------------------------------------------------------------- + */ + case 'xlsx': + case 'xlsm': + case 'xltx': + case 'xltm': + return 'Excel2007'; + break; + + /* + |-------------------------------------------------------------------------- + | Excel5 + |-------------------------------------------------------------------------- + */ + case 'xls': + case 'xlt': + return 'Excel5'; + break; + + /* + |-------------------------------------------------------------------------- + | OOCalc + |-------------------------------------------------------------------------- + */ + case 'ods': + case 'ots': + return 'OOCalc'; + break; + + /* + |-------------------------------------------------------------------------- + | SYLK + |-------------------------------------------------------------------------- + */ + case 'slk': + return 'SYLK'; + break; + + /* + |-------------------------------------------------------------------------- + | Excel2003XML + |-------------------------------------------------------------------------- + */ + case 'xml': + return 'Excel2003XML'; + break; + + /* + |-------------------------------------------------------------------------- + | Gnumeric + |-------------------------------------------------------------------------- + */ + case 'gnumeric': + return 'Gnumeric'; + break; + + /* + |-------------------------------------------------------------------------- + | HTML + |-------------------------------------------------------------------------- + */ + case 'htm': + case 'html': + return 'HTML'; + break; + + /* + |-------------------------------------------------------------------------- + | CSV + |-------------------------------------------------------------------------- + */ + case 'csv': + case 'txt': + return 'CSV'; + break; + + /* + |-------------------------------------------------------------------------- + | PDF + |-------------------------------------------------------------------------- + */ + // case 'pdf': + // return 'PDF'; + // break; + } + } + + /** + * Get the content type by file format + * @param string $format [description] + * @return string $contentType + */ + public function getContentTypeByFormat($format) + { + switch($format) + { + + /* + |-------------------------------------------------------------------------- + | Excel 2007 + |-------------------------------------------------------------------------- + */ + case 'Excel2007': + return'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'; + break; + + /* + |-------------------------------------------------------------------------- + | Excel5 + |-------------------------------------------------------------------------- + */ + case 'Excel5': + return'application/vnd.ms-excel; charset=UTF-8'; + break; + + /* + |-------------------------------------------------------------------------- + | HTML + |-------------------------------------------------------------------------- + */ + case 'HTML': + return 'HTML'; + break; + + /* + |-------------------------------------------------------------------------- + | CSV + |-------------------------------------------------------------------------- + */ + case 'CSV': + return'application/csv; charset=UTF-8'; + break; + + /* + |-------------------------------------------------------------------------- + | PDF + |-------------------------------------------------------------------------- + */ + // case 'PDF': + // return'application/pdf; charset=UTF-8'; + // break; + } + } + + /** + * Try every reader we have + * @return string $format + */ + protected function lastResort($file, $wrongFormat = false) + { + // Loop through all available formats + foreach ($this->formats as $format) + { + // Check if the file could be read + if($wrongFormat != $format && $this->canRead($format, $file)) + return $format; + } + + // Give up searching and throw an exception + throw new LaravelExcelException('[ERROR] Reader could not identify file format for file ['. $file .'] with extension [' . $ext . ']'); + } + + /** + * Check if we can read the file + * @return boolean + */ + protected function canRead($format, $file) + { + if($format) + { + $reader = $this->initReader($format); + return $reader && $reader->canRead($file); + } + + return false; + } + + /** + * Init the reader based on the format + * @param string $format + * @return Reader + */ + protected function initReader($format) + { + return PHPExcel_IOFactory::createReader($format); + } + + /** + * Get the file extension + * @param string $file + * @return string + */ + protected function getExtension($file) + { + return strtolower($this->filesystem->extension($file)); + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index ee7a8e27a..a2c2c3f67 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -1,15 +1,16 @@ bindClasses(); $this->bindReaders(); $this->bindParsers(); $this->bindPHPExcelClass(); @@ -58,11 +60,10 @@ public function register() /** * Bind PHPExcel classes - * @return [type] [description] + * @return void */ protected function bindPHPExcelClass() { - // Set object $me = $this; @@ -82,14 +83,14 @@ protected function bindPHPExcelClass() /** * Bind writers - * @return [type] [description] + * @return void */ protected function bindReaders() { // Bind the laravel excel reader $this->app['excel.reader'] = $this->app->share(function($app) { - return new LaravelExcelReader($app['files']); + return new LaravelExcelReader($app['files'], $app['excel.identifier']); }); // Bind the html reader class @@ -101,7 +102,7 @@ protected function bindReaders() /** * Bind writers - * @return [type] [description] + * @return void */ protected function bindParsers() { @@ -114,20 +115,20 @@ protected function bindParsers() /** * Bind writers - * @return [type] [description] + * @return void */ protected function bindWriters() { // Bind the excel writer $this->app['excel.writer'] = $this->app->share(function($app) { - return new LaravelExcelWriter($app->make('Response'), $app['files']); + return new LaravelExcelWriter($app->make('Response'), $app['files'], $app['excel.identifier']); }); } /** * Bind Excel class - * @return [type] [description] + * @return void */ protected function bindExcel() { @@ -139,7 +140,20 @@ protected function bindExcel() } /** - * Set the cache settings + * Bind other classes + * @return [type] [description] + */ + protected function bindClasses() + { + // Bind the format identifier + $this->app['excel.identifier'] = $this->app->share(function($app) { + return new FormatIdentifier($app['files']); + }); + } + + /** + * Set cache settings + * @return Maatwebsite\Excel\Classes\Cache */ public function setCacheSettings() { diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index b00e49a22..43da4c893 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -1,10 +1,11 @@ filesystem = $filesystem; + $this->identifier = $identifier; } /** @@ -578,64 +580,10 @@ public function needsDateFormatting() */ protected function _setFormat() { - $this->format = $this->identify($this->file); + $this->format = $this->identifier->getFormatByFile($this->file); return $this; } - /** - * Identify file format - * @return [type] [description] - */ - protected function identify($file) - { - switch ($this->getExtension($file)) { - case 'xlsx': - case 'xlsm': - case 'xltx': - case 'xltm': - return 'Excel2007'; - break; - case 'xls': - case 'xlt': - return 'Excel5'; - break; - case 'ods': - case 'ots': - return 'OOCalc'; - break; - case 'slk': - return 'SYLK'; - break; - case 'xml': - return 'Excel2003XML'; - break; - case 'gnumeric': - return 'Gnumeric'; - break; - case 'htm': - case 'html': - return 'HTML'; - break; - case 'csv': - case 'txt': - return 'CSV'; - break; - } - - throw new LaravelExcelException('[ERROR] Reader could not identify file format for file ['. $file .'].'); - - } - - /** - * Get the file extension - * @param [type] $file [description] - * @return [type] [description] - */ - protected function getExtension($file) - { - return strtolower($this->filesystem->extension($file)); - } - /** * Parse the file * @return [type] [description] diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 8ad8bd901..f97c0220d 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -1,10 +1,11 @@ response = $response; $this->filesystem = $filesystem; + $this->identifier = $identifier; } /** @@ -346,30 +348,14 @@ protected function _setAttribute($setter, $params) */ protected function _setFormat() { + // Get extension $this->ext = strtolower($this->ext); - switch($this->ext) - { - case 'xls': - $this->format = 'Excel5'; - $this->contentType = 'application/vnd.ms-excel; charset=UTF-8'; - break; - - case 'xlsx': - $this->format = 'Excel2007'; - $this->contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'; - break; - - case 'csv': - $this->format = 'CSV'; - $this->contentType = 'application/csv; charset=UTF-8'; - break; - - default: - $this->format = 'Excel5'; - $this->contentType = 'application/vnd.ms-excel; charset=UTF-8'; - break; - } + // get the file format + $this->format = $this->identifier->getFormatByExtension($this->ext); + + // Get content type + $this->contentType = $this->identifier->getContentTypeByFormat($this->format); } /** From 171dd2a044d0f513a0cc65222f85bdb383621b5e Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 28 May 2014 22:11:22 +0200 Subject: [PATCH 0146/1332] Update changelog --- README.md | 2 +- docs/changelog/version-1.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 64e0a3a6c..d90b4f135 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.7 +## Laravel Excel v1.0.8 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index f02034c1c..1f2bffc34 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.0.8 + +- File format identifier enhancements + ### 1.0.7 - Set workbook properties fix From 71581ec3d4b4a5dd2b3a1d51f0a914579a094ef9 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 29 May 2014 17:38:12 +0200 Subject: [PATCH 0147/1332] Prepend and append rows --- .../Excel/Classes/LaravelExcelWorksheet.php | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index c87dc7f23..4dd758cb4 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -162,6 +162,47 @@ public function row($rowNumber, $callback = false) return $this; } + /** + * Prepend a row + * @param integer $rowNumber + * @param array|closure $callback + * @return object $this + */ + public function prependRow($rowNumber = 1, $callback = null) + { + // If only one param was given, prepend it before the first row + if(is_null($callback)) + { + $callback = $rowNumber; + $rowNumber = 1; + } + + // Create new row + $this->insertNewRowBefore($rowNumber); + + // Add data to row + return $this->row($rowNumber, $callback); + } + + /** + * Append a row + * @param integer $rowNumber + * @param array|closure $callback + * @return object $this + */ + public function appendRow($rowNumber = 1, $callback = null) + { + // If only one param was given, add it as very last + if(is_null($callback)) + { + $callback = $rowNumber; + $rowNumber = $this->getHighestRow() + 1; + } + + // Add the row + return $this->row($rowNumber, $callback); + } + /** * Manipulate a single cell * @param [type] $cell [description] From fa9cd5e975acbbe17352a05f88426ff1a3f46b6c Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 29 May 2014 17:54:53 +0200 Subject: [PATCH 0148/1332] Add multiple rows --- .../Excel/Classes/LaravelExcelWorksheet.php | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 4dd758cb4..78964fa25 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -162,6 +162,26 @@ public function row($rowNumber, $callback = false) return $this; } + /** + * Add multiple rows + * @param array $rows [description] + * @return [type] [description] + */ + public function rows($rows = array()) + { + // Get the start row + $startRow = $this->getStartRow(); + + // Add rows + foreach($rows as $row) + { + $this->row($startRow, $row); + $startRow++; + } + + return $this; + } + /** * Prepend a row * @param integer $rowNumber @@ -196,7 +216,7 @@ public function appendRow($rowNumber = 1, $callback = null) if(is_null($callback)) { $callback = $rowNumber; - $rowNumber = $this->getHighestRow() + 1; + $rowNumber = $this->getStartRow(); } // Add the row @@ -877,6 +897,18 @@ public function setMergeColumn(Array $mergeColumn) return $this; } + /** + * Return the start row + * @return [type] [description] + */ + protected function getStartRow() + { + if($this->getHighestRow() == 1) + return 1; + + return $this->getHighestRow() + 1; + } + /** * Dynamically call methods * @param [type] $method [description] From 0bd516b9793ed5389ca721a46f8be1c441aa43b2 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 29 May 2014 18:24:39 +0200 Subject: [PATCH 0149/1332] Config settings for strict null comparision for array export, fixes issue #135 --- .../Excel/Classes/LaravelExcelWorksheet.php | 48 +++++++++++++++++++ src/config/export.php | 30 ++++++++++++ 2 files changed, 78 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 78964fa25..1c449dcd0 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -365,6 +365,26 @@ public function fromModel($source = NULL, $headingGeneration = true) return parent::fromArray($this->data); } + /** + * Fill worksheet from values in array + * + * @param array $source Source array + * @param mixed $nullValue Value in source array that stands for blank cell + * @param string $startCell Insert array starting from this cell address as the top left coordinate + * @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function fromArray($source = null, $nullValue = null, $startCell = false, $strictNullComparison = false) + { + // Set defaults + $nullValue = !is_null($nullValue) ? $nullValue : $this->getDefaultNullValue(); + $startCell = $startCell ? $startCell : $this->getDefaultStartCell(); + $strictNullComparison = $strictNullComparison ? $strictNullComparison : $this->getDefaultStrictNullComparison(); + + return parent::fromArray($source, $nullValue, $startCell, $strictNullComparison); + } + /** * Add vars to the data array * @param [type] $key [description] @@ -909,6 +929,34 @@ protected function getStartRow() return $this->getHighestRow() + 1; } + /** + * Return default null value + * @return string/integer/null + */ + protected function getDefaultNullValue() + { + return Config::get('excel::export.sheets.nullValue', null); + } + + /** + * Return default null value + * @return string/integer/null + */ + protected function getDefaultStartCell() + { + return Config::get('excel::export.sheets.startCell', 'A1'); + } + + + /** + * Return default strict null comparison + * @return boolean + */ + protected function getDefaultStrictNullComparison() + { + return Config::get('excel::export.sheets.strictNullComparison', false); + } + /** * Dynamically call methods * @param [type] $method [description] diff --git a/src/config/export.php b/src/config/export.php index cb625cde2..b308ff28d 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -24,6 +24,36 @@ */ 'generate_heading_by_indices' => true, + + /* + |-------------------------------------------------------------------------- + | Default sheet settings + |-------------------------------------------------------------------------- + */ + 'sheets' => array( + + /* + |-------------------------------------------------------------------------- + | Value in source array that stands for blank cell + |-------------------------------------------------------------------------- + */ + 'nullValue' => null, + + /* + |-------------------------------------------------------------------------- + | Insert array starting from this cell address as the top left coordinate + |-------------------------------------------------------------------------- + */ + 'startCell' => 'A2', + + /* + |-------------------------------------------------------------------------- + | Apply strict comparison when testing for null values in the array + |-------------------------------------------------------------------------- + */ + 'strictNullComparison' => false + ), + /* |-------------------------------------------------------------------------- | Store settings From 3d8a842a379367c4cc418503a9dd395a7c07c669 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 30 May 2014 14:26:13 +0200 Subject: [PATCH 0150/1332] Blade to Excel export fix for PHP5.3, fixes issue #137 --- README.md | 2 +- docs/changelog/version-1.md | 4 ++++ src/Maatwebsite/Excel/Readers/HtmlReader.php | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d90b4f135..03b17644c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.8 +## Laravel Excel v1.0.9 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 1f2bffc34..627ed76c4 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.0.9 + +- Blade to Excel export fix for PHP5.3 + ### 1.0.8 - File format identifier enhancements diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 18b8af57e..a9f3761b1 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -143,7 +143,7 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, else { // Load HTML from string - $loaded = @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8'), PHPExcel_Settings::getLibXmlLoaderOptions()); + $loaded = @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8')); } if ($loaded === FALSE) From 3e0a70da88ac44f6be944650e5dcfa4de70059b3 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Fri, 30 May 2014 14:26:13 +0200 Subject: [PATCH 0151/1332] Blade to Excel export fix for PHP5.3, fixes issue #137 --- README.md | 2 +- docs/changelog/version-1.md | 4 ++++ src/Maatwebsite/Excel/Readers/HtmlReader.php | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d90b4f135..03b17644c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.8 +## Laravel Excel v1.0.9 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 1f2bffc34..627ed76c4 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.0.9 + +- Blade to Excel export fix for PHP5.3 + ### 1.0.8 - File format identifier enhancements diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index aa39ae5b0..6d9cc1819 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -142,7 +142,7 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, else { // Load HTML from string - $loaded = @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8'), PHPExcel_Settings::getLibXmlLoaderOptions()); + $loaded = @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8')); } if ($loaded === FALSE) From 76768ef6e325fb706d321d804ce5a0ab8592f436 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 31 May 2014 20:29:02 +0200 Subject: [PATCH 0152/1332] Worksheet IDE autocomplete update --- src/Maatwebsite/Excel/Classes/Cache.php | 14 +- .../Excel/Classes/FormatIdentifier.php | 4 +- .../Excel/Classes/LaravelExcelWorksheet.php | 198 ++++++++++-------- src/Maatwebsite/Excel/Excel.php | 6 +- .../Excel/ExcelServiceProvider.php | 2 +- 5 files changed, 123 insertions(+), 101 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/Cache.php b/src/Maatwebsite/Excel/Classes/Cache.php index ed7219468..784d3347f 100644 --- a/src/Maatwebsite/Excel/Classes/Cache.php +++ b/src/Maatwebsite/Excel/Classes/Cache.php @@ -1,8 +1,8 @@ Date: Sun, 1 Jun 2014 16:47:34 +0200 Subject: [PATCH 0153/1332] IDE autocomplete updates, fixes issue #87 --- src/Maatwebsite/Excel/Classes/PHPExcel.php | 14 +- .../Excel/Collections/CellCollection.php | 7 +- src/Maatwebsite/Excel/Excel.php | 1 + .../Exceptions/LaravelExcelException.php | 2 +- src/Maatwebsite/Excel/Facades/Excel.php | 2 +- src/Maatwebsite/Excel/Parsers/CssParser.php | 54 +++-- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 81 ++++--- src/Maatwebsite/Excel/Parsers/ViewParser.php | 29 +-- src/Maatwebsite/Excel/Readers/Batch.php | 27 ++- .../Excel/Readers/ConfigReader.php | 41 ++-- src/Maatwebsite/Excel/Readers/HtmlReader.php | 213 +++++++++--------- .../Excel/Readers/LaravelExcelReader.php | 173 +++++++------- src/Maatwebsite/Excel/Writers/CellWriter.php | 61 +++-- .../Excel/Writers/LaravelExcelWriter.php | 109 +++++---- 14 files changed, 431 insertions(+), 383 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index ddbdcf79d..b9bb33f38 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -1,7 +1,7 @@ excel = $excel; @@ -61,8 +64,8 @@ public function __construct($excel, $config = 'excel::import', $callback = false /** * Start the import - * @param boolean $callback [description] - * @return [type] [description] + * @param callback $callback + * @return void */ public function start($callback = false) { @@ -97,7 +100,7 @@ public function start($callback = false) /** * Get the sheet collection - * @return [type] [description] + * @return SheetCollection */ public function getSheetCollection() { @@ -106,8 +109,8 @@ public function getSheetCollection() /** * Get value by index - * @param [type] $field [description] - * @return [type] [description] + * @param string $field + * @return string|null */ protected function valueByIndex($field) { @@ -126,8 +129,8 @@ protected function valueByIndex($field) /** * Return cell value - * @param [type] $coordinate [description] - * @return [type] [description] + * @param string $coordinate + * @return string|null */ protected function getCellValueByCoordinate($coordinate) { @@ -151,8 +154,8 @@ protected function getCellValueByCoordinate($coordinate) /** * Get the coordinates from the config file - * @param [type] $field [description] - * @return [type] [description] + * @param string $field + * @return string|boolean */ protected function getCoordinateByKey($field) { @@ -161,8 +164,8 @@ protected function getCoordinateByKey($field) /** * Dynamically get a value by config - * @param [type] $field [description] - * @return [type] [description] + * @param string $field + * @return string */ public function __get($field) { diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index a9f3761b1..84a7dc425 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -1,21 +1,21 @@ _tableLevel == 0) $column = 'A'; @@ -612,7 +614,7 @@ private function _setTableStartColumn($column) /** * Get the table start column - * @return [type] [description] + * @return string */ private function _getTableStartColumn() { @@ -621,7 +623,7 @@ private function _getTableStartColumn() /** * Release the table start column - * @return [type] [description] + * @return array */ private function _releaseTableStartColumn() { @@ -631,11 +633,11 @@ private function _releaseTableStartColumn() /** * Flush the cells - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $cellContent [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param string $cellContent + * @return void */ private function _flushCell($sheet,$column,$row,&$cellContent) { @@ -663,11 +665,11 @@ private function _flushCell($sheet,$column,$row,&$cellContent) /** * Process table headings - * @param [type] $child [description] - * @param [type] $sheet [description] - * @param [type] $row [description] - * @param [type] $column [description] - * @return [type] [description] + * @param string $child + * @param LaravelExcelWorksheet $sheet + * @param string $row + * @param integer $column + * @return LaravelExcelWorksheet */ protected function _processHeadings($child, $sheet, $row, $column, $cellContent) { @@ -684,11 +686,11 @@ protected function _processHeadings($child, $sheet, $row, $column, $cellContent) /** * Style the element by class - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $class [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param string $class + * @return void */ protected function styleByClass($sheet, $column, $row, $class) { @@ -715,11 +717,11 @@ protected function styleByClass($sheet, $column, $row, $class) /** * Style the element by class - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $class [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param string $class + * @return void */ protected function styleById($sheet, $column, $row, $class) { @@ -733,11 +735,11 @@ protected function styleById($sheet, $column, $row, $class) /** * Insert a image inside the sheet - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $src [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param string $attributes + * @return void */ protected function insertImageBySrc($sheet, $column, $row, $attributes) { @@ -771,11 +773,11 @@ protected function insertImageBySrc($sheet, $column, $row, $attributes) /** * Set column width - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $width [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param integer $width + * @return void */ protected function parseWidth($sheet, $column, $row, $width) { @@ -784,11 +786,11 @@ protected function parseWidth($sheet, $column, $row, $width) /** * Set row height - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $height [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param integer $height + * @return void */ protected function parseHeight($sheet, $column, $row, $height) { @@ -797,11 +799,11 @@ protected function parseHeight($sheet, $column, $row, $height) /** * Parse colspans - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $tag [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param integer $spanWidth + * @return void */ protected function parseColSpan($sheet, $column, $row, $spanWidth) { @@ -827,11 +829,11 @@ protected function parseColSpan($sheet, $column, $row, $spanWidth) /** * Parse colspans - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $tag [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param integer $spanHeight + * @return void */ protected function parseRowSpan($sheet, $column, $row, $spanHeight) { @@ -847,11 +849,11 @@ protected function parseRowSpan($sheet, $column, $row, $spanHeight) /** * Parse the align - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $value [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param string $value + * @return void */ protected function parseAlign($sheet, $column, $row, $value) { @@ -886,11 +888,11 @@ protected function parseAlign($sheet, $column, $row, $value) /** * Parse the valign - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $value [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param string $value + * @return void */ protected function parseValign($sheet, $column, $row, $value) { @@ -925,11 +927,11 @@ protected function parseValign($sheet, $column, $row, $value) /** * Parse the inline styles - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $styleTag [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param string $styleTag + * @return void */ protected function parseInlineStyles($sheet, $column, $row, $styleTag) { @@ -941,11 +943,11 @@ protected function parseInlineStyles($sheet, $column, $row, $styleTag) /** * Parse the styles - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $styles [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param array @styles + * @return void */ protected function parseCssAttributes($sheet, $column, $row, $styles = array()) { @@ -961,12 +963,12 @@ protected function parseCssAttributes($sheet, $column, $row, $styles = array()) /** * Parse CSS - * @param [type] $sheet [description] - * @param [type] $column [description] - * @param [type] $row [description] - * @param [type] $name [description] - * @param [type] $value [description] - * @return [type] [description] + * @param LaravelExcelWorksheet $sheet + * @param string $column + * @param integer $row + * @param string $name + * @param string $value + * @return void */ protected function parseCssProperties($sheet, $column, $row, $name, $value) { @@ -1178,8 +1180,8 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) /** * Get the color - * @param [type] $color [description] - * @return [type] [description] + * @param string $color + * @return string */ public function getColor($color) { @@ -1190,13 +1192,12 @@ public function getColor($color) $color = $color . $color; return $color; - } /** * Get the border style - * @param [type] $style [description] - * @return [type] [description] + * @param string $style + * @return string */ public function borderStyle($style) { diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index ef7fbb260..67481d0e1 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -23,19 +23,19 @@ class LaravelExcelReader { /** * Excel object - * @var [type] + * @var PHPExcel */ public $excel; /** * Spreadsheet writer - * @var [type] + * @var object */ public $reader; /** * The file to read - * @var [type] + * @var string */ public $file; @@ -47,7 +47,7 @@ class LaravelExcelReader { /** * Spreadsheet title - * @var [type] + * @var string */ public $title; @@ -65,25 +65,25 @@ class LaravelExcelReader { /** * Default format - * @var [type] + * @var stirng */ public $format; /** * The parsed file - * @var [type] + * @var SheetCollection|RowCollection */ public $parsed; /** * Delimiter - * @var [type] + * @var string */ public $delimiter; /** * Calculate [true/false] - * @var [type] + * @var boolean */ public $calculate; @@ -166,10 +166,9 @@ public function __construct(Filesystem $filesystem, FormatIdentifier $identifier /** * Load a file - * @param [type] $file [description] - * @param boolean $firstRowAsIndex [description] - * @param string $inputEncoding [description] - * @return [type] [description] + * @param string $file + * @param boolean $firstRowAsIndex + * @return LaravelExcelReader */ public function load($file, $encoding = false) { @@ -189,7 +188,7 @@ public function load($file, $encoding = false) /** * set selected sheets - * @param [type] $sheets [description] + * @param array $sheets */ public function setSelectedSheets($sheets) { @@ -198,7 +197,7 @@ public function setSelectedSheets($sheets) /** * Check if sheets were selected - * @return [type] [description] + * @return integer */ public function sheetsSelected() { @@ -207,8 +206,8 @@ public function sheetsSelected() /** * Remember the results for x minutes - * @param [type] $minutes [description] - * @return [type] [description] + * @param integer $minutes + * @return LaravelExcelReader */ public function remember($minutes) { @@ -219,11 +218,11 @@ public function remember($minutes) /** * Read the file through a config file - * @param [type] $config [description] - * @param boolean $callback [description] - * @return [type] [description] + * @param stirng $config + * @param callback|null $callback + * @return SheetCollection */ - public function byConfig($config, $callback = false) + public function byConfig($config, $callback = null) { $config = new ConfigReader($this->excel, $config, $callback); return $config->getSheetCollection(); @@ -231,8 +230,8 @@ public function byConfig($config, $callback = false) /** * Take x rows - * @param [type] $amount [description] - * @return [type] [description] + * @param integer $amount + * @return LaravelExcelReader */ public function take($amount) { @@ -243,8 +242,8 @@ public function take($amount) /** * Skip x rows - * @param [type] $amount [description] - * @return [type] [description] + * @param integer $amount + * @return LaravelExcelReader */ public function skip($amount) { @@ -255,9 +254,9 @@ public function skip($amount) /** * Limit the results by x - * @param [type] $take [description] - * @param [type] $skip [description] - * @return [type] [description] + * @param integer $take + * @param integer $skip + * @return LaravelExcelReader */ public function limit($take, $skip = 0) { @@ -272,8 +271,8 @@ public function limit($take, $skip = 0) /** * Select certain columns - * @param array $columns [description] - * @return [type] [description] + * @param array $columns + * @return LaravelExcelReader */ public function select($columns = array()) { @@ -283,7 +282,8 @@ public function select($columns = array()) /** * Return all sheets/rows - * @return [type] [description] + * @param array $columns + * @return LaravelExcelReader */ public function all($columns = array()) { @@ -292,7 +292,8 @@ public function all($columns = array()) /** * Get first row/sheet only - * @return [type] [description] + * @param array $columns + * @return SheetCollection|RowCollection */ public function first($columns = array()) { @@ -301,7 +302,8 @@ public function first($columns = array()) /** * Get all sheets/rows - * @return [type] [description] + * @param array $columns + * @return SheetCollection|RowCollection */ public function get($columns = array()) { @@ -323,8 +325,8 @@ public function get($columns = array()) /** * Each - * @param [type] $callback [description] - * @return [type] [description] + * @param callback $callback + * @return SheetCollection|RowCollection */ public function each($callback) { @@ -332,11 +334,9 @@ public function each($callback) } /** - * * Parse the file to an array. - * - * @return array $this->parsed The parsed array - * + * @param array $columns + * @return array */ public function toArray($columns = array()) { @@ -344,11 +344,9 @@ public function toArray($columns = array()) } /** - * * Parse the file to an object. - * - * @return obj $this->parsed The parsed object - * + * @param array $columns + * @return SheetCollection|RowCollection */ public function toObject($columns = array()) { @@ -356,11 +354,9 @@ public function toObject($columns = array()) } /** - * * Dump the parsed file to a readable array - * - * @return array $this->parsed The parsed array - * + * @param array $columns + * @param boolean $die */ public function dump($columns = array(), $die = false) { @@ -371,7 +367,7 @@ public function dump($columns = array(), $die = false) /** * Die and dump - * @return [type] [description] + * @param array $columns */ public function dd($columns = array()) { @@ -380,10 +376,9 @@ public function dd($columns = array()) /** * Init the loading - * @param [type] $file [description] - * @param [type] $firstRowAsIndex [description] - * @param [type] $inputEncoding [description] - * @return [type] [description] + * @param string $file + * @param string|boolean $firstRowAsIndex + * @return void */ protected function _init($file, $encoding = false) { @@ -398,8 +393,8 @@ protected function _init($file, $encoding = false) /** * Inject the excel object - * @param [type] $excel [description] - * @return [type] [description] + * @param PHPExcel $excel + * @return void */ public function injectExcel($excel) { @@ -409,7 +404,8 @@ public function injectExcel($excel) /** * Set the file - * @param [type] $file [description] + * @param string $file + * @return LaraveExcelReader */ protected function _setFile($file) { @@ -423,7 +419,8 @@ protected function _setFile($file) /** * Set the spreadsheet title - * @param [type] $title [description] + * @param string|boolean $title + * @return LaraveExcelReader */ public function setTitle($title = false) { @@ -433,7 +430,8 @@ public function setTitle($title = false) /** * Set extension - * @param [type] $ext [description] + * @param string|boolean $ext + * @return LaraveExcelReader */ public function setExtension($ext = false) { @@ -443,7 +441,8 @@ public function setExtension($ext = false) /** * Set the date format - * @param str $format The date format + * @param string $format The date format + * @return LaraveExcelReader */ public function setDateFormat($format = false) { @@ -454,7 +453,9 @@ public function setDateFormat($format = false) /** * Enable/disable date formating - * @param bool $boolean True/false + * @param boolean $boolean True/false + * @param boolean $format + * @return LaraveExcelReader */ public function formatDates($boolean = true, $format = false) { @@ -465,6 +466,7 @@ public function formatDates($boolean = true, $format = false) /** * Set the date columns + * @return LaraveExcelReader */ public function setDateColumns() { @@ -476,8 +478,8 @@ public function setDateColumns() /** * If the file has a table heading or not - * @param [type] $boolean [description] - * @return [type] [description] + * @param boolean $boolean + * @return LaraveExcelReader */ public function noHeading($boolean = true) { @@ -487,7 +489,8 @@ public function noHeading($boolean = true) /** * Set the cell name word seperator - * @param [type] $seperator [description] + * @param string $seperator + * @return LaraveExcelReader */ public function setSeperator($seperator) { @@ -498,6 +501,8 @@ public function setSeperator($seperator) /** * Set the delimiter * Calling this after the ->load() will have no effect + * @param string $delimiter + * @return LaraveExcelReader */ public function setDelimiter($delimiter) { @@ -506,12 +511,9 @@ public function setDelimiter($delimiter) } /** - * * Set default calculate - * * @param bool $boolean Calculate yes or no - * @return $this - * + * @return LaraveExcelReader */ public function calculate($boolean = true) { @@ -521,8 +523,8 @@ public function calculate($boolean = true) /** * Ignore empty cells - * @param boolean $boolean [description] - * @return [type] [description] + * @param boolean $boolean + * @return LaraveExcelReader */ public function ignoreEmpty($boolean = true) { @@ -532,7 +534,7 @@ public function ignoreEmpty($boolean = true) /** * Check if the file has een heading - * @return boolean [description] + * @return boolean */ public function hasHeading() { @@ -544,7 +546,7 @@ public function hasHeading() /** * Get the seperator - * @return [type] [description] + * @return string */ public function getSeperator() { @@ -556,7 +558,7 @@ public function getSeperator() /** * Get the dateFormat - * @return [type] [description] + * @return string */ public function getDateFormat() { @@ -565,7 +567,7 @@ public function getDateFormat() /** * Get the date columns - * @return [type] [description] + * @return array */ public function getDateColumns() { @@ -574,7 +576,7 @@ public function getDateColumns() /** * Check if we need to calculate the formula inside the cell - * @return [type] [description] + * @return boolean */ public function needsCalculation() { @@ -583,7 +585,7 @@ public function needsCalculation() /** * Check if we need to ignore the empty cells - * @return [type] [description] + * @return boolean */ public function needsIgnoreEmpty() { @@ -592,7 +594,7 @@ public function needsIgnoreEmpty() /** * Check if we need to format the dates - * @return [type] [description] + * @return boolean */ public function needsDateFormatting() { @@ -601,7 +603,7 @@ public function needsDateFormatting() /** * Return the amount of rows to skip - * @return [type] [description] + * @return integer */ public function getSkip() { @@ -610,7 +612,7 @@ public function getSkip() /** * Return the amount of rows to take - * @return [type] [description] + * @return integer */ public function getLimit() { @@ -619,6 +621,7 @@ public function getLimit() /** * Set the write format + * @return LaraveExcelReader */ protected function _setFormat() { @@ -628,7 +631,8 @@ protected function _setFormat() /** * Parse the file - * @return [type] [description] + * @param array $columns + * @return void */ protected function _parseFile($columns = array()) { @@ -642,6 +646,7 @@ protected function _parseFile($columns = array()) /** * Set the writer + * @return LaraveExcelReader */ protected function _setReader() { @@ -653,7 +658,8 @@ protected function _setReader() /** * Set the input encoding - * @param boolean $encoding [description] + * @param boolean $encoding + * @return LaraveExcelReader */ protected function _setInputEncoding($encoding = false) { @@ -669,6 +675,7 @@ protected function _setInputEncoding($encoding = false) /** * Set reader defaults + * @return void */ protected function _setReaderDefaults() { @@ -698,7 +705,7 @@ protected function _setReaderDefaults() /** * Reset the writer - * @return [type] [description] + * @return void */ protected function _reset() { @@ -707,7 +714,7 @@ protected function _reset() /** * Get excel object - * @return [type] [description] + * @return PHPExcel */ public function getExcel() { @@ -716,9 +723,9 @@ public function getExcel() /** * Dynamically call methods - * @param [type] $method [description] - * @param [type] $params [description] - * @return [type] [description] + * @param string $method + * @param array $params + * @throws LaravelExcelException */ public function __call($method, $params) { diff --git a/src/Maatwebsite/Excel/Writers/CellWriter.php b/src/Maatwebsite/Excel/Writers/CellWriter.php index 785a1b70a..4dcf883f0 100644 --- a/src/Maatwebsite/Excel/Writers/CellWriter.php +++ b/src/Maatwebsite/Excel/Writers/CellWriter.php @@ -17,20 +17,20 @@ class CellWriter { /** * Current $sheet - * @var [type] + * @var LaravelExcelWorksheet */ public $sheet; /** * Selected cells - * @var [type] + * @var array */ public $cells; /** * Constructor - * @param [type] $cells [description] - * @param LaravelExcelWorksheet $sheet [description] + * @param [type] $cells + * @param LaravelExcelWorksheet $sheet */ public function __construct($cells, LaravelExcelWorksheet $sheet) { @@ -40,7 +40,8 @@ public function __construct($cells, LaravelExcelWorksheet $sheet) /** * Set cell value - * @param [type] $value [description] + * @param [type] $value + * @return CellWriter */ public function setValue($value) { @@ -55,9 +56,10 @@ public function setValue($value) /** * Set the background - * @param [type] $color [description] - * @param string $type [description] - * @param string $colorType [description] + * @param string $color + * @param string $type + * @param string $colorType + * @return CellWriter */ public function setBackground($color, $type = 'solid', $colorType = 'rgb') { @@ -66,8 +68,9 @@ public function setBackground($color, $type = 'solid', $colorType = 'rgb') /** * Set the font color - * @param [type] $color [description] - * @param string $colorType [description] + * @param string $color + * @param string $colorType + * @return CellWriter */ public function setFontColor($color, $colorType = 'rgb') { @@ -76,7 +79,8 @@ public function setFontColor($color, $colorType = 'rgb') /** * Set the font - * @param [type] $right [description] + * @param array $right + * @return CellWriter */ public function setFont($styles) { @@ -85,7 +89,8 @@ public function setFont($styles) /** * Set font family - * @param [type] $family [description] + * @param string $family + * @return CellWriter */ public function setFontFamily($family) { @@ -96,6 +101,8 @@ public function setFontFamily($family) /** * Set font size + * @param string $size + * @return CellWriter */ public function setFontSize($size) { @@ -106,10 +113,11 @@ public function setFontSize($size) /** * Set border - * @param [type] $top [description] - * @param boolean $right [description] - * @param boolean $bottom [description] - * @param boolean $left [description] + * @param string $top + * @param boolean $right + * @param boolean $bottom + * @param boolean $left + * @return CellWriter */ public function setBorder($top = 'none', $right = 'none', $bottom = 'none', $left = 'none') { @@ -136,7 +144,8 @@ public function setBorder($top = 'none', $right = 'none', $bottom = 'none', $lef /** * Set the alignment - * @param [type] $alignment [description] + * @param string $alignment + * @return CellWriter */ public function setAlignment($alignment) { @@ -147,7 +156,8 @@ public function setAlignment($alignment) /** * Set vertical alignment - * @param [type] $alignment [description] + * @param string $alignment + * @return CellWriter */ public function setValignment($alignment) { @@ -158,10 +168,11 @@ public function setValignment($alignment) /** * Set the color style - * @param [type] $style [description] - * @param [type] $color [description] - * @param boolean $type [description] - * @param string $colorType [description] + * @param string $style + * @param string $color + * @param boolean $type + * @param string $colorType + * @return CellWriter */ protected function setColorStyle($styleType, $color, $type = false, $colorType = 'rgb') { @@ -176,7 +187,9 @@ protected function setColorStyle($styleType, $color, $type = false, $colorType = /** * Set style - * @param [type] $styles [description] + * @param string $styles + * @param array $styles + * @return CellWriter */ protected function setStyle($styleType, $styles) { @@ -193,7 +206,7 @@ protected function setStyle($styleType, $styles) /** * Get the cell style - * @return [type] [description] + * @return PHPExcel_Style */ protected function getCellStyle() { diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 263fd5bd3..301fb8f2d 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -1,6 +1,7 @@ response = $response; $this->filesystem = $filesystem; - $this->identifier = $identifier; + $this->identifier = $identifier; } /** * Inject the excel object - * @param [type] $excel [description] - * @return [type] [description] + * @param PHPExcel $excel + * @return void */ public function injectExcel($excel, $reset = true) { @@ -109,7 +111,8 @@ public function injectExcel($excel, $reset = true) /** * Set the spreadsheet title - * @param [type] $title [description] + * @param string $title + * @return LaravelExcelWriter */ public function setTitle($title) { @@ -120,7 +123,7 @@ public function setTitle($title) /** * Get the title - * @return [type] [description] + * @return string */ public function getTitle() { @@ -128,8 +131,11 @@ public function getTitle() } /** - * Share a view with all sheets - * @return [type] [description] + * Share view with all sheets + * @param string $view + * @param array $data + * @param array $mergeData + * @return LaravelExcelWriter */ public function shareView($view, $data = array(), $mergeData = array()) { @@ -146,6 +152,7 @@ public function shareView($view, $data = array(), $mergeData = array()) /** * Set the view + * @return LaravelExcelWriter */ public function setView() { @@ -154,7 +161,7 @@ public function setView() /** * Load the view - * @return [type] [description] + * @return LaravelExcelWriter */ public function loadView() { @@ -163,11 +170,11 @@ public function loadView() /** * Create a new sheet - * @param [type] $title [description] - * @param [type] $callback [description] - * @return [type] [description] + * @param string $title + * @param callback|null $callback + * @return LaravelExcelWriter */ - public function sheet($title, $callback = false) + public function sheet($title, $callback = null) { // Clone the active sheet $this->sheet = $this->excel->createSheet(null, $title); @@ -183,7 +190,7 @@ public function sheet($title, $callback = false) $this->sheet->setDefaultPageSetup(); // Do the callback - if($callback instanceof \Closure) + if($callback instanceof Closure) call_user_func($callback, $this->sheet); // Autosize columns when it hasn't been done yet @@ -198,9 +205,8 @@ public function sheet($title, $callback = false) /** * Set data for the current sheet - * @param [type] $keys [description] - * @param boolean $value [description] - * @return [type] [description] + * @param array $array + * @return LaravelExcelWriter */ public function with(Array $array) { @@ -211,7 +217,8 @@ public function with(Array $array) /** * Export the spreadsheet - * @return [type] [description] + * @param string $ext + * @return void */ public function export($ext = 'xls') { @@ -227,8 +234,8 @@ public function export($ext = 'xls') /** * Export and download the spreadsheet - * @param string $ext [description] - * @return [type] [description] + * @param string $ext + * @return void */ public function download($ext = 'xls') { @@ -237,7 +244,7 @@ public function download($ext = 'xls') /** * Download a file - * @return [type] [description] + * @return void */ protected function _download() { @@ -266,10 +273,10 @@ protected function _download() /** * Store the excel file to the server - * @param string $ext [description] - * @param boolean $path [description] - * @param boolean $returnInfo [description] - * @return [type] [description] + * @param string $ext + * @param boolean $path + * @param boolean $returnInfo + * @return LaravelExcelWriter */ public function store($ext = 'xls', $path = false, $returnInfo = false) { @@ -306,7 +313,11 @@ public function store($ext = 'xls', $path = false, $returnInfo = false) return $this; } - // Check if we want to return info or itself + /** + * Check if we want to return info or itself + * @param boolean $returnInfo + * @return boolean + */ public function returnInfo($returnInfo = false) { return $returnInfo ? $returnInfo : Config::get('excel::export.store.returnInfo', false); @@ -316,7 +327,7 @@ public function returnInfo($returnInfo = false) * Store the excel file to the server * @param str $ext The file extension * @param str $path The save path - * @return $this + * @return LaravelExcelWriter */ public function save($ext = 'xls', $path = false, $returnInfo = false) { @@ -325,7 +336,7 @@ public function save($ext = 'xls', $path = false, $returnInfo = false) /** * Start render of a new spreadsheet - * @return [type] [description] + * @return void */ protected function _render() { @@ -345,7 +356,7 @@ protected function _render() /** * Get the view parser - * @return [type] [description] + * @return PHPExcel */ public function getExcel() { @@ -354,7 +365,7 @@ public function getExcel() /** * Get the view parser - * @return [type] [description] + * @return ViewParser */ public function getParser() { @@ -367,7 +378,7 @@ public function getParser() /** * Get the sheet - * @return [type] [description] + * @return LaravelExcelWorksheet */ public function getSheet() { @@ -376,8 +387,8 @@ public function getSheet() /** * Set attributes - * @param [type] $setter [description] - * @param [type] $params [description] + * @param string $setter + * @param array $params */ protected function _setAttribute($setter, $params) { @@ -394,6 +405,7 @@ protected function _setAttribute($setter, $params) /** * Set the write format + * @return void */ protected function _setFormat() { @@ -409,6 +421,7 @@ protected function _setFormat() /** * Set the writer + * @return PHPExcel_***_Writer */ protected function _setWriter() { @@ -440,7 +453,7 @@ protected function _setHeaders($headers) /** * Set the storage path - * @var [type] + * @return void */ protected function _setStoragePath($path = false) { @@ -457,7 +470,7 @@ protected function _setStoragePath($path = false) /** * Reset the writer - * @return [type] [description] + * @return void */ protected function _reset() { @@ -466,9 +479,9 @@ protected function _reset() /** * Dynamically call methods - * @param [type] $method [description] - * @param [type] $params [description] - * @return [type] [description] + * @param string $method + * @param array $params + * @return LaravelExcelWriter */ public function __call($method, $params) { From 1fc24fbef38878ad3a8989332b4416598d3bd4f7 Mon Sep 17 00:00:00 2001 From: Ismail BASKIN Date: Fri, 6 Jun 2014 00:37:52 +0300 Subject: [PATCH 0154/1332] Created package installer JSON config file --- provides.json | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 provides.json diff --git a/provides.json b/provides.json new file mode 100644 index 000000000..d7f2a9d2c --- /dev/null +++ b/provides.json @@ -0,0 +1,11 @@ +{ + "providers": [ + "Maatwebsite\Excel\ExcelServiceProvider" + ], + "aliases": [ + { + "alias": "Excel", + "facade": "Maatwebsite\Excel\Facades\Excel" + } + ] +} \ No newline at end of file From 980c942c34617967adf39908b2a8b3c266474511 Mon Sep 17 00:00:00 2001 From: Luke Armstrong Date: Fri, 6 Jun 2014 12:17:12 +0100 Subject: [PATCH 0155/1332] set default config for CSV enclosure to be quoted --- src/Maatwebsite/Excel/Readers/LaravelExcelReader.php | 2 +- src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php | 2 +- src/config/csv.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 67481d0e1..b9c4082c1 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -683,7 +683,7 @@ protected function _setReaderDefaults() if($this->format == 'CSV') { $this->reader->setDelimiter(Config::get('excel::csv.delimiter', ',')); - $this->reader->setEnclosure(Config::get('excel::csv.enclosure', '')); + $this->reader->setEnclosure(Config::get('excel::csv.enclosure', '"')); $this->reader->setLineEnding(Config::get('excel::csv.line_ending', "\r\n")); } diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 301fb8f2d..e7e1b576d 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -431,7 +431,7 @@ protected function _setWriter() if($this->format == 'CSV') { $this->writer->setDelimiter(Config::get('excel::csv.delimiter', ',')); - $this->writer->setEnclosure(Config::get('excel::csv.enclosure', '')); + $this->writer->setEnclosure(Config::get('excel::csv.enclosure', '"')); $this->writer->setLineEnding(Config::get('excel::csv.line_ending', "\r\n")); } diff --git a/src/config/csv.php b/src/config/csv.php index 1e4365c72..a80a80982 100644 --- a/src/config/csv.php +++ b/src/config/csv.php @@ -19,7 +19,7 @@ |-------------------------------------------------------------------------- */ - 'enclosure' => '', + 'enclosure' => '"', /* |-------------------------------------------------------------------------- From 560e13e515c4d027ce57a490275e5629da825632 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 16:33:45 +0200 Subject: [PATCH 0156/1332] Set column width for view files (setWidth() + inline width=) fixes issue #118 --- composer.json | 2 +- .../Excel/Classes/LaravelExcelWorksheet.php | 15 ++++++++++----- src/Maatwebsite/Excel/Readers/HtmlReader.php | 4 +++- .../Excel/Writers/LaravelExcelWriter.php | 4 ++-- 4 files changed, 16 insertions(+), 9 deletions(-) diff --git a/composer.json b/composer.json index 5560bd96a..669b7ff51 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "require-dev": { "phpunit/phpunit": "~4.0", "mockery/mockery": "~0.9", - "orchestra/testbench": "~2.1.1" + "orchestra/testbench": "~2.2.0@dev" }, "autoload": { "classmap": [ diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index ac04a8e58..dce58b3e8 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -84,7 +84,7 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet * Check if the file was autosized * @var boolean */ - public $wasAutoSized = false; + public $hasFixedSizeColumns = false; /** * Auto generate table heading @@ -683,7 +683,12 @@ public function setWidth($column, $value = false) else { // Disable the autosize and set column width - $this->getColumnDimension($column)->setAutoSize(false)->setWidth($value); + $this->getColumnDimension($column) + ->setAutoSize(false) + ->setWidth($value); + + // Set autosized to true + $this->hasFixedSizeColumns = true; } return $this; @@ -757,7 +762,7 @@ public function setSize($cell, $width = false, $height = false) public function setAutoSize($columns = false) { // Remember that the sheet was autosized - $this->wasAutoSized = true; + $this->hasFixedSizeColumns = true; // Set autosize to true $this->autoSize = $columns ? $columns : false; @@ -804,9 +809,9 @@ public function getAutosize() * Check if the sheet was auto sized dynamically * @return boolean */ - public function wasAutoSized() + public function hasFixedSizeColumns() { - return $this->wasAutoSized ? true : false; + return $this->hasFixedSizeColumns ? true : false; } /** diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 84a7dc425..afe8af497 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -163,7 +163,9 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, $column = 'A'; $content = ''; $this->_processDomElement($dom,$sheet,$row,$column,$content); - $this->autosizeColumn($sheet); + + if(!$sheet->hasFixedSizeColumns()) + $this->autosizeColumn($sheet); return $sheet; } diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index e7e1b576d..b0f55e479 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -193,8 +193,8 @@ public function sheet($title, $callback = null) if($callback instanceof Closure) call_user_func($callback, $this->sheet); - // Autosize columns when it hasn't been done yet - if(!$this->sheet->wasAutoSized()) + // Autosize columns when no user didn't change anything about column sizing + if(!$this->sheet->hasFixedSizeColumns()) $this->sheet->setAutosize(Config::get('excel::export.autosize', false)); // Parse the sheet From d18b2beb2e6024ad66853e566195eb992145924e Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 16:42:55 +0200 Subject: [PATCH 0157/1332] Make to ASCII conversion for header columns optional, fixes issue #140 --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 17 ++++++++++++----- src/config/import.php | 13 ++++++++++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 80212af6b..fc8e53249 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -183,10 +183,17 @@ protected function getIndices() $this->indices = array(); // Loop through the cells - foreach ($this->row->getCellIterator() as $this->cell) { - + foreach ($this->row->getCellIterator() as $this->cell) + { // Set labels - $this->indices[] = Str::slug($this->cell->getValue(), $this->reader->getSeperator()); + if(Config::get('excel::import.to_ascii', true)) + { + $this->indices[] = Str::slug($this->cell->getValue(), $this->reader->getSeperator()); + } + else + { + $this->indices[] = strtolower(str_replace(array(' '), $this->reader->getSeperator(), $this->cell->getValue())); + } } // Return the labels @@ -206,8 +213,8 @@ protected function parseRows() $startRow = $this->getStartRow(); // Loop through the rows inside the worksheet - foreach ($this->worksheet->getRowIterator($startRow) as $this->row) { - + foreach ($this->worksheet->getRowIterator($startRow) as $this->row) + { // Limit the results when needed if($this->hasReachedLimit()) break; diff --git a/src/config/import.php b/src/config/import.php index 58dbf0f19..17a8149cb 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -7,7 +7,7 @@ | Has heading |-------------------------------------------------------------------------- | - | The sheet has a heading row which we can use as attribute names + | The sheet has a heading (first) row which we can use as attribute names | */ @@ -24,6 +24,17 @@ 'seperator' => '_', + /* + |-------------------------------------------------------------------------- + | Sheet heading conversion + |-------------------------------------------------------------------------- + | + | Convert headings to ASCII + | + */ + + 'to_ascii' => true, + /* |-------------------------------------------------------------------------- | Import encoding From 8cda527939a9ad5e85ed850a57f37a8c81938f40 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 16:46:58 +0200 Subject: [PATCH 0158/1332] Documentation typo setAllBorders, fixes issue #132 --- docs/export/sheet-styling.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/export/sheet-styling.md b/docs/export/sheet-styling.md index 950496cba..296bbb932 100644 --- a/docs/export/sheet-styling.md +++ b/docs/export/sheet-styling.md @@ -39,7 +39,7 @@ To change the font for the current sheet use `->setFont($array)`: You can set borders for the sheet, by using: // Sets all borders - $sheet->setAllBorder('thin'); + $sheet->setAllBorders('thin'); // Set border for cells $sheet->setBorder('A1', 'thin'); From 78df90621a009f78e56ee8782382ed6a9f11918d Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 16:49:26 +0200 Subject: [PATCH 0159/1332] Throw exception on missing ->set*() methods --- src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index dce58b3e8..826c65762 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -549,6 +549,8 @@ public function _setAttributes($setter, $params) { $this->setDefaultStyles($setter, $key, $params); } + + throw new LaravelExcelException('[ERROR] Laravel Worksheet method ['. $setter .'] does not exist.'); } /** From d5174cb03d8073abad5f842ad4763eee17d578b1 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 17:18:25 +0200 Subject: [PATCH 0160/1332] Make fromModel compatible with fromArray() to add autoHeadingGeneration from fromArray, fixes issue #139 --- .../Excel/Classes/LaravelExcelWorksheet.php | 38 +++++++++++-------- src/config/export.php | 2 +- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 826c65762..d91213525 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -359,16 +359,9 @@ public function with($key, $value = false, $headingGeneration = true) * @param boolean $headingGeneration * @return LaravelExcelWorksheet */ - public function fromModel($source = NULL, $headingGeneration = true) + public function fromModel($source = NULL, $nullValue = null, $startCell = false, $strictNullComparison = false, $headingGeneration = true) { - // Set the heading generation setting - $this->setAutoHeadingGeneration($headingGeneration); - - // Add the vars - $this->_addVars($source); - - // create from array - return parent::fromArray($this->data); + return $this->fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration); } /** @@ -381,14 +374,20 @@ public function fromModel($source = NULL, $headingGeneration = true) * @throws PHPExcel_Exception * @return LaravelExcelWorksheet */ - public function fromArray($source = null, $nullValue = null, $startCell = false, $strictNullComparison = false) + public function fromArray($source = null, $nullValue = null, $startCell = false, $strictNullComparison = false, $headingGeneration = true) { // Set defaults - $nullValue = !is_null($nullValue) ? $nullValue : $this->getDefaultNullValue(); - $startCell = $startCell ? $startCell : $this->getDefaultStartCell(); + $nullValue = !is_null($nullValue) ? $nullValue : $this->getDefaultNullValue(); + $startCell = $startCell ? $startCell : $this->getDefaultStartCell(); $strictNullComparison = $strictNullComparison ? $strictNullComparison : $this->getDefaultStrictNullComparison(); - return parent::fromArray($source, $nullValue, $startCell, $strictNullComparison); + // Set the heading generation setting + $this->setAutoHeadingGeneration($headingGeneration); + + // Add the vars + $this->_addVars($source); + + return parent::fromArray($this->data, $nullValue, $startCell, $strictNullComparison); } /** @@ -407,7 +406,12 @@ protected function _addVars($key, $value = false) // Create excel from array without a view if(!$this->parser) - return $this->fromArray($this->data); + { + $nullValue = $this->getDefaultNullValue(); + $startCell = $this->getDefaultStartCell(); + $strictNullComparison = $this->getDefaultStrictNullComparison(); + return parent::fromArray($this->data, $nullValue, $startCell, $strictNullComparison); + } } // Add seperate values @@ -485,8 +489,12 @@ protected function addData($array) } + // Add results + if(!empty($data)) + $this->data = !empty($this->data) ? array_merge($this->data, $data) : $data; + // return data - return array_merge($this->data, $data); + return $this->data; } /** diff --git a/src/config/export.php b/src/config/export.php index b308ff28d..8b2474ac0 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -44,7 +44,7 @@ | Insert array starting from this cell address as the top left coordinate |-------------------------------------------------------------------------- */ - 'startCell' => 'A2', + 'startCell' => 'A1', /* |-------------------------------------------------------------------------- From 84499e302d1e0a7fa0b8cd1ef61ba94817facb3f Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 17:31:21 +0200 Subject: [PATCH 0161/1332] Set alignment on merged cells, fixes issue #113 --- .../Excel/Classes/LaravelExcelWorksheet.php | 23 +++++++++++++++++-- src/config/export.php | 7 ++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index d91213525..691af016d 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -935,16 +935,35 @@ public function setColumnFormat(Array $formats){ return $this; } + /** + * Merge cells + * @param string $pRange [description] + * @return [type] [description] + */ + public function mergeCells($pRange = 'A1:A1', $alignment = false) + { + // Merge the cells + parent::mergeCells($pRange); + + // Set center alignment on merge cells + $this->cells($pRange, function($cell) use ($alignment) { + $aligment = is_string($alignment) ? $alignment : Config::get('excel::export.merged_cell_alignment', 'left'); + $cell->setAlignment($aligment); + }); + + return $this; + } + /** * Set the columns you want to merge * @return LaravelExcelWorksheet * @param array $mergeColumn An array of columns you want to merge */ - public function setMergeColumn(Array $mergeColumn) + public function setMergeColumn(Array $mergeColumn, $alignment = false) { foreach ($mergeColumn['columns'] as $column) { foreach ($mergeColumn['rows'] as $row) { - $this->mergeCells($column.$row[0].":".$column.$row[1]); + $this->mergeCells($column.$row[0].":".$column.$row[1], $alignment); } } diff --git a/src/config/export.php b/src/config/export.php index 8b2474ac0..3fad7ac0c 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -25,6 +25,13 @@ 'generate_heading_by_indices' => true, + /* + |-------------------------------------------------------------------------- + | Auto set aligment on merged cells + |-------------------------------------------------------------------------- + */ + 'merged_cell_alignment' => 'left', + /* |-------------------------------------------------------------------------- | Default sheet settings From ae3ba5b0cce71f000e969760dedaaebc90df0751 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 17:48:41 +0200 Subject: [PATCH 0162/1332] Set default page margins, fixes issue #114 --- .../Excel/Classes/LaravelExcelWorksheet.php | 34 +++++++++++++++++++ src/config/export.php | 15 +++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 691af016d..39cd0aa0e 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -125,6 +125,40 @@ public function setDefaultPageSetup() if(!is_null($value)) call_user_func_array(array($pageSetup, $setter), array($value)); } + + // Set default page margins + $this->setPageMargin(Config::get('excel::export.sheets.page_margin', false)); + } + + /** + * Set the page margin + * @param array $margin [description] + */ + public function setPageMargin($margin = false) + { + if(!is_array($margin)) + { + $marginArray = array($margin, $margin, $margin, $margin); + } + else + { + $marginArray = $margin; + } + + // Get margin + $pageMargin = $this->getPageMargins(); + + if(isset($marginArray[0])) + $pageMargin->setTop($marginArray[0]); + + if(isset($marginArray[1])) + $pageMargin->setRight($marginArray[1]); + + if(isset($marginArray[2])) + $pageMargin->setBottom($marginArray[2]); + + if(isset($marginArray[3])) + $pageMargin->setLeft($marginArray[3]); } /** diff --git a/src/config/export.php b/src/config/export.php index 3fad7ac0c..c6b3c5f3f 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -24,7 +24,6 @@ */ 'generate_heading_by_indices' => true, - /* |-------------------------------------------------------------------------- | Auto set aligment on merged cells @@ -39,6 +38,20 @@ */ 'sheets' => array( + /* + |-------------------------------------------------------------------------- + | Default page margin + |-------------------------------------------------------------------------- + | + | 1) When set to false, default margins will be used + | 2) It's possible to enter a single margin which will + | be used for all margins. + | 3) Alternativly you can pass an array with 4 margins + | Default order: array(top, right, bottom, left) + | + */ + 'page_margin' => false, + /* |-------------------------------------------------------------------------- | Value in source array that stands for blank cell From f488351124382fd6826380ba79714f7ef1129d8a Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 17:59:40 +0200 Subject: [PATCH 0163/1332] Manipulate cells inside a row with CellWriter --- .../Excel/Classes/LaravelExcelWorksheet.php | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 39cd0aa0e..426412fa8 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -170,8 +170,11 @@ public function setPageMargin($margin = false) public function row($rowNumber, $callback = null) { // If a callback is given, handle it with the cell writer - //if($callback instanceof Closure) - //return $this->rows($rowNumber, $callback); + if($callback instanceof Closure) + { + $range = $this->rowToRange($rowNumber); + return $this->cells($range, $callback); + } // Else if the 2nd param was set, we will use it as a cell value if(is_array($callback)) @@ -1016,6 +1019,15 @@ protected function getStartRow() return $this->getHighestRow() + 1; } + /** + * Return range from row + * @return [type] [description] + */ + protected function rowToRange($rowNumber) + { + return 'A' . $rowNumber . ':' . $this->getHighestColumn() . $rowNumber; + } + /** * Return default null value * @return string|integer|null From ab0e4d9a5d71c8e7dde6c0f8e28091dc762d4cf2 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 18:00:39 +0200 Subject: [PATCH 0164/1332] Remove travis php5.3 test --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index f0d36ff27..c1b4cce46 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 5.3 - 5.4 - 5.5 From 9f8cda7feac54ea943c8699a2e1e1cad002bacc6 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 18:09:36 +0200 Subject: [PATCH 0165/1332] Update changelog --- docs/changelog/version-1.md | 19 +++++++++++++++++++ .../Excel/Classes/LaravelExcelWorksheet.php | 9 +++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 627ed76c4..e77651d7e 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,24 @@ # Version 1 +### 1.1.0 + +- `Limit()`, `skip()` and `take()` support for fetching results +- Set default page margins +- Export Eloquent models directly (`fromModel()`) +- Auto generate the first row (table heading) from the array keys +- Manipulate cells and cell ranges inside a closure +- Set cell backgrounds/fonts/values, ... +- Create/append/prepend new row/rows +- Manipulate row cells (background, fonts, ...) +- Config value default alignment on merge cells +- DocBlock updates to support better use of IDE autocomplete features +- Parse width and height inside views +- Parse images in views +- Optional to ASCII conversion of imported header columns (array indices) +- Config values for default null comparision and start cells for exports +- Changed default CSV enclosure to `"` +- Support for Laravel package installer + ### 1.0.9 - Blade to Excel export fix for PHP5.3 diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 426412fa8..d44ecbc51 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -132,7 +132,7 @@ public function setDefaultPageSetup() /** * Set the page margin - * @param array $margin [description] + * @param array|boolean|integer|float $margin */ public function setPageMargin($margin = false) { @@ -974,8 +974,8 @@ public function setColumnFormat(Array $formats){ /** * Merge cells - * @param string $pRange [description] - * @return [type] [description] + * @param string $pRange + * @return LaravelExcelWorksheet */ public function mergeCells($pRange = 'A1:A1', $alignment = false) { @@ -1021,7 +1021,8 @@ protected function getStartRow() /** * Return range from row - * @return [type] [description] + * @param integer $rowNumber + * @return string $range */ protected function rowToRange($rowNumber) { From ccd00fba3e515925dfce092867dcccc3b1b298e3 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 18:10:39 +0200 Subject: [PATCH 0166/1332] Update version number in readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 03b17644c..e86390a61 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.0.9 +## Laravel Excel v1.1.0 [](http://www.maatwebsite.nl/laravel-excel/docs) From 52552342dddbf9c4e74153183fca781163fe4756 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 18:18:28 +0200 Subject: [PATCH 0167/1332] Docs update part 1 --- docs/export/array.md | 19 ++++++++++++++++--- docs/export/sheets.md | 17 ++++++++++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/docs/export/array.md b/docs/export/array.md index 3e2c3dc79..6213a27aa 100644 --- a/docs/export/array.md +++ b/docs/export/array.md @@ -1,6 +1,8 @@ # Creating a sheet from an array -To create a new file from an array use `->fromArray()` inside the sheet closure. +## Array + +To create a new file from an array use `->fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration)` inside the sheet closure. Excel::create('Filename', function($excel) { @@ -41,9 +43,20 @@ If you want to pass variables inside the closure, use `use($data)` ### Null comparision -By default 0 is shown as an empty cell. If you want to change this behaviour, you can pass true as 4 parameter: +By default 0 is shown as an empty cell. If you want to change this behaviour, you can pass true as 4th parameter: // Will show 0 as 0 $sheet->fromArray($data, null, 'A1', true); ->> To change the default behaviour, you can use `excel::export.sheets.strictNullComparison` config setting. \ No newline at end of file +>> To change the default behaviour, you can use `excel::export.sheets.strictNullComparison` config setting. + +## Eloquent model + +It's also possible to pass an Eloquent model and export it by using `->fromModel($model)`. The method accepts the same parameters as fromArray + +## Auto heading generation + +By default the export will use the keys of your array (or model attribute names) as first row (header column). To change this behaviour you can edit the default config setting (`excel::export.generate_heading_by_indices`) or pass `false` as 5th parameter: + + // Won't auto generate heading columns + $sheet->fromArray($data, null, 'A1', false, false); \ No newline at end of file diff --git a/docs/export/sheets.md b/docs/export/sheets.md index b1c63421b..9a6cbaa36 100644 --- a/docs/export/sheets.md +++ b/docs/export/sheets.md @@ -47,4 +47,19 @@ There are a couple of properties we can change inside the closure. Most of them })->export('xls'); -> Go to the reference guide to see a list of available properties. \ No newline at end of file +> Go to the reference guide to see a list of available properties. + +### Default page margin + +It's possible to set the default page margin insde the config file `excel::export.sheets`. +It accepts boolean, single value or array. + +To manually set the page margin you can use: `->setPageMargin()` + + // Set top, right, bottom, left + $sheet->setPageMargin(array( + 0.25, 0.30, 0.25, 0.30 + )); + + // Set all margins + $sheet->setPageMargin(0.25); \ No newline at end of file From b531e4700a0786edaec761c7c3d94332f7f59e3e Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 19:01:20 +0200 Subject: [PATCH 0168/1332] Set font weight for cells/rows --- docs/export.md | 2 + docs/export/cells.md | 33 +++++++++- docs/export/rows.md | 63 ++++++++++++++++++++ src/Maatwebsite/Excel/Writers/CellWriter.php | 12 ++++ 4 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 docs/export/rows.md diff --git a/docs/export.md b/docs/export.md index d2408211d..5e2908068 100644 --- a/docs/export.md +++ b/docs/export.md @@ -3,6 +3,8 @@ @include:Store to server|store @include:Creating Sheets|sheets @include:Creatings Sheets From array|array +@include:Row manipulation|rows +@include:Cell manipulation|cells @include:Sheet styling|sheet-styling @include:Freeze rows|freeze @include:Auto filter|autofilter diff --git a/docs/export/cells.md b/docs/export/cells.md index 2adee5440..f1052b6dc 100644 --- a/docs/export/cells.md +++ b/docs/export/cells.md @@ -1,7 +1,38 @@ # Cell manipulation + $sheet->cell('A1', function($cell) { + + // manipulate the cell + + }); + $sheet->cells('A1:A5', function($cells) { // manipulate the range of cells - }); \ No newline at end of file + }); + +### Set background + +To change the background of a range of cells we can use `->setBackground($color, $type, $colorType)` + + // Set black background + $cells->setBackground('#000000'); + +### Change fonts + + // Set with font color + $cells->setFontColor('#ffffff'); + + // Set font family + $cells->setFontFamily('Calibri'); + + // Set font size + $cells->setFontSize(16); + + // Set font + $cells->setFont(array( + 'family' => 'Calibri', + 'size' => '16', + 'bold' => true + )); \ No newline at end of file diff --git a/docs/export/rows.md b/docs/export/rows.md new file mode 100644 index 000000000..587931492 --- /dev/null +++ b/docs/export/rows.md @@ -0,0 +1,63 @@ +# Row manipulation + +### Manipulate certain row + +#### Change cell values + + // Manipulate first row + $sheet->row(1, array( + 'test1', 'test2' + )); + + // Manipulate 2nd row + $sheet->row(2, array( + 'test3', 'test4' + )); + +#### Manipulate row cells + + // Set black background + $sheet->row(1, function($row) { + + // call cell manipulation methods + $row->setBackground('#000000'); + + }); + +### Append row + + // Append row after row 2 + $sheet->appendRow(2, array( + 'appended', 'appended' + )); + + // Append row as very last + $sheet->appendRow(array( + 'appended', 'appended' + )); + +### Prepend row + + // Add before first row + $sheet->prependRow(1, array( + 'prepended', 'prepended' + )); + + // Add as very first + $sheet->prependRow(array( + 'prepended', 'prepended' + )); + +### Append multiple rows + + // Append multiple rows + $sheet->rows(array( + array('test1', 'test2'), + array('test3', 'test4') + )); + + // Append multiple rows + $sheet->rows(array( + array('test5', 'test6'), + array('test7', 'test8') + )); \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Writers/CellWriter.php b/src/Maatwebsite/Excel/Writers/CellWriter.php index 4dcf883f0..6db0bedbc 100644 --- a/src/Maatwebsite/Excel/Writers/CellWriter.php +++ b/src/Maatwebsite/Excel/Writers/CellWriter.php @@ -111,6 +111,18 @@ public function setFontSize($size) )); } + /** + * Set font weight + * @param boolean|string $bold + * @return CellWriter + */ + public function setFontWeight($bold = true) + { + return $this->setStyle('font', array( + 'bold' => ($bold == 'bold' || $bold) ? true : false + )); + } + /** * Set border * @param string $top From 387c1d6d99c80a2dffdd974969421b8fa142a893 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 19:13:38 +0200 Subject: [PATCH 0169/1332] Update docs --- docs/blade/styling.md | 7 +++++++ docs/export/cells.md | 29 ++++++++++++++++++++++++++++- docs/export/export.md | 4 +++- docs/reference-guide.md | 3 ++- docs/reference-guide/closures.md | 10 ++++++++++ docs/reference-guide/css-styles.md | 4 +++- 6 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 docs/reference-guide/closures.md diff --git a/docs/blade/styling.md b/docs/blade/styling.md index 880e66c80..7c37bfcfc 100644 --- a/docs/blade/styling.md +++ b/docs/blade/styling.md @@ -44,6 +44,8 @@ Most of the HTML tags are supported. Italic cell + + @@ -67,6 +69,11 @@ Some of the basic styling can be done with HTML attributes. Italic cell + + Cell with width of 100 + + + Cell with height of 100 diff --git a/docs/export/cells.md b/docs/export/cells.md index f1052b6dc..f2a41513b 100644 --- a/docs/export/cells.md +++ b/docs/export/cells.md @@ -30,9 +30,36 @@ To change the background of a range of cells we can use `->setBackground($color, // Set font size $cells->setFontSize(16); + // Set font weight to bold + $cells->setFontWeight('bold'); + // Set font $cells->setFont(array( 'family' => 'Calibri', 'size' => '16', 'bold' => true - )); \ No newline at end of file + )); + +### Set borders + + // Set all borders (top, right, bottom, left) + $cells->setBorder('solid', 'none', 'none', 'solid'); + + // Set borders with array + $cells->setBorder(array( + 'borders' => array( + 'top' => array( + 'style' => 'solid' + ), + ) + )); + +### Set horizontal alignment + + // Set alignment to center + $cells->setAlignment('center'); + +### Set vertical alignment + + // Set vertical alignment to middle + $cells->setValignment('middle'); \ No newline at end of file diff --git a/docs/export/export.md b/docs/export/export.md index b5c744f7d..bb21afcce 100644 --- a/docs/export/export.md +++ b/docs/export/export.md @@ -23,4 +23,6 @@ To download the created file, use `->export($ext)` or `->download($ext)`. ->export('csv'); // or - ->download('csv'); \ No newline at end of file + ->download('csv'); + +> You can set the default enclosure and delimiter inside the config \ No newline at end of file diff --git a/docs/reference-guide.md b/docs/reference-guide.md index 8df2b4eb0..4fe22b728 100644 --- a/docs/reference-guide.md +++ b/docs/reference-guide.md @@ -2,4 +2,5 @@ @include:Available sheet properties|sheet-properties @include:Available CSS styles|css-styles @include:Available border styles|borders -@include:Available column formatting|formatting \ No newline at end of file +@include:Available column formatting|formatting +@include:Closures|closures \ No newline at end of file diff --git a/docs/reference-guide/closures.md b/docs/reference-guide/closures.md new file mode 100644 index 000000000..8719d3f2f --- /dev/null +++ b/docs/reference-guide/closures.md @@ -0,0 +1,10 @@ +# Closures + +| Method | Closure class | +| ------------- |-------------| +| create() | Maatwebsite\Excel\Writers\LaravelExcelWriter | +| load() | Maatwebsite\Excel\Readers\LaravelExcelReader | +| batch | Maatwebsite\Excel\Readers\Batch | +| sheet() | Maatwebsite\Excel\Classes\LaravelExcelWorksheet | +| cells() | Maatwebsite\Excel\Writers\CellWriter | +| row() | Maatwebsite\Excel\Writers\CellWriter | \ No newline at end of file diff --git a/docs/reference-guide/css-styles.md b/docs/reference-guide/css-styles.md index 7a98fbdf1..2498adbe1 100644 --- a/docs/reference-guide/css-styles.md +++ b/docs/reference-guide/css-styles.md @@ -14,4 +14,6 @@ Styles that can be used inside an external CSS file or as inline CSS. | text-decoration | underline | | text-align | center | | vertical-align | middle | -| border(-*) | 1px dashed #CCC | \ No newline at end of file +| border(-*) | 1px dashed #CCC | +| width | 100(px) | +| height | 1100(px) | \ No newline at end of file From 92cf68fb486ae04be204fea363c40bc7fc7f11a1 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Sat, 7 Jun 2014 19:29:21 +0200 Subject: [PATCH 0170/1332] Change contribution details --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e86390a61..517e2c2e6 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ The complete documentation can be found at: [http://www.maatwebsite.nl/laravel-e # Contributing -**ALL** bug fixes should be made to the `dev-develop` branch. Bug fixes should never be sent to the `master` branch. +**ALL** bug fixes should be made to appropriate branch (e.g. `1.1` for 1.1.* bug fixes). Bug fixes should never be sent to the `master` branch. More about contributing can be found at: [http://www.maatwebsite.nl/laravel-excel/docs/getting-started#contributing](http://www.maatwebsite.nl/laravel-excel/docs/getting-started#contributing) From b0fa99f2af61325e4ebbccd65a0de3fc3f7327c2 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Sat, 7 Jun 2014 19:30:07 +0200 Subject: [PATCH 0171/1332] Change contribution details --- docs/getting-started/contributing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/getting-started/contributing.md b/docs/getting-started/contributing.md index 6a6737f25..825f06aa0 100644 --- a/docs/getting-started/contributing.md +++ b/docs/getting-started/contributing.md @@ -2,7 +2,7 @@ ### Bug fixes -**ALL** bug fixes should be made to the `dev-develop` branch. Bug fixes should never be sent to the `master` branch. +**ALL** bug fixes should be made to appropriate branch (e.g. `1.1` for 1.1.* bug fixes). Bug fixes should never be sent to the `master` branch. ### Pull Requests From 9aae3ea0d9dab99435da7921bfc0bd7f42223327 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 7 Jun 2014 20:35:29 +0200 Subject: [PATCH 0172/1332] Reader + CSV Reader testing --- tests/Readers/CsvReaderTest.php | 309 ++++++++++++++++++++++++++++++ tests/Readers/ReaderTest.php | 33 ++++ tests/Readers/test.csv | 6 + tests/Writers/ExcelWriterTest.php | 9 + 4 files changed, 357 insertions(+) create mode 100644 tests/Readers/CsvReaderTest.php create mode 100644 tests/Readers/ReaderTest.php create mode 100644 tests/Readers/test.csv diff --git a/tests/Readers/CsvReaderTest.php b/tests/Readers/CsvReaderTest.php new file mode 100644 index 000000000..427c772f1 --- /dev/null +++ b/tests/Readers/CsvReaderTest.php @@ -0,0 +1,309 @@ +excel = App::make('phpexcel'); + + // Set writer class + $this->reader = App::make('excel.reader'); + $this->reader->injectExcel($this->excel); + + // Load csv file + $this->loadCsv(); + } + + /** + * Test loading a csv file + * @return [type] [description] + */ + public function testLoadCsv() + { + $this->assertEquals($this->reader, $this->loadedCsv); + $this->assertInstanceOf('PHPExcel', $this->reader->getExcel()); + } + + /** + * Test get + * @return [type] [description] + */ + public function testGet() + { + $got = $this->loadedCsv->get(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); + $this->assertCount(5, $got); + } + + /** + * Test get with columns + * @return [type] [description] + */ + public function testGetWithColumns() + { + $columns = array('heading1', 'heading2'); + $got = $this->loadedCsv->get($columns); + + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); + $this->assertCount(5, $got); + } + + /** + * Test all + * @return [type] [description] + */ + public function testAll() + { + $all = $this->loadedCsv->all(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $all); + $this->assertCount(5, $all); + } + + /** + * Test first + * @return [type] [description] + */ + public function testFirst() + { + $first = $this->loadedCsv->first(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); + + // 3 columns + $this->assertCount(3, $first); + } + + /** + * Test first with columns + * @return [type] [description] + */ + public function testFirstWithColumns() + { + $columns = array('heading1', 'heading2'); + $first = $this->loadedCsv->first($columns); + + $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); + $this->assertCount(count($columns), $first); + } + + /** + * Test each + * @return [type] [description] + */ + public function testEach() + { + $me = $this; + + $this->loadedCsv->each(function($cells) use($me) { + + $me->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $cells); + + }); + } + + /** + * Test toArray + * @return [type] [description] + */ + public function testToArray() + { + $array = $this->loadedCsv->toArray(); + $this->assertEquals(array( + + array( + 'heading1' => 'test', + 'heading2' => 'test', + 'heading3' => 'test', + ), + array( + 'heading1' => 'test', + 'heading2' => 'test', + 'heading3' => 'test', + ), + array( + 'heading1' => 'test', + 'heading2' => 'test', + 'heading3' => 'test', + ), + array( + 'heading1' => 'test', + 'heading2' => 'test', + 'heading3' => 'test', + ), + array( + 'heading1' => 'test', + 'heading2' => 'test', + 'heading3' => 'test', + ) + + ), $array); + } + + /** + * Test remember method + * @return [type] [description] + */ + public function testRemember() + { + $remembered = $this->loadedCsv->remember(10); + + $this->assertEquals($this->reader, $remembered); + $this->assertEquals(10, $remembered->cacheMinutes); + $this->assertTrue($remembered->remembered); + } + + /** + * Test set selected sheets + * @return [type] [description] + */ + public function testByConfig() + { + $config = $this->loadedCsv->byConfig('excel::import.sheets'); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); + } + + /** + * Test set selected sheets + * @return [type] [description] + */ + public function testByConfigCallback() + { + $me = $this; + + $config = $this->loadedCsv->byConfig('excel::import.sheets', function($config) use($me) + { + $me->assertInstanceOf('Maatwebsite\Excel\Readers\ConfigReader', $config); + }); + + $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); + } + + /** + * Test take + * @return [type] [description] + */ + public function testTake() + { + $taken = $this->loadedCsv->take(2); + $this->assertEquals(2, $taken->getLimit()); + $this->assertCount(2, $taken->get()); + } + + /** + * Test limit + * @return [type] [description] + */ + public function testSkip() + { + $taken = $this->loadedCsv->skip(1); + $this->assertEquals(1, $taken->getSkip()); + $this->assertCount(4, $taken->get()); + } + + /** + * Test limit + * @return [type] [description] + */ + public function testLimit() + { + $taken = $this->loadedCsv->limit(2, 1); + $this->assertEquals(2, $taken->getLimit()); + $this->assertEquals(1, $taken->getSkip()); + $this->assertCount(2, $taken->get()); + } + + /** + * Test select columns + * @return [type] [description] + */ + public function testSelect() + { + $columns = array('heading1', 'heading2'); + + $taken = $this->loadedCsv->select($columns); + $this->assertEquals($columns, $taken->columns); + } + + /** + * Test set date format + * @return [type] [description] + */ + public function testSetDateFormat() + { + $set = $this->loadedCsv->setDateFormat('Y-m-d'); + $this->assertEquals('Y-m-d', $set->getDateFormat()); + } + + public function testFormatDates() + { + $set = $this->loadedCsv->formatDates(true, 'Y-m-d'); + $this->assertTrue($set->needsDateFormatting()); + $this->assertEquals('Y-m-d', $set->getDateFormat()); + } + + public function testSetDateColumns() + { + $set = $this->loadedCsv->setDateColumns('created_at', 'deleted_at'); + $this->assertTrue($set->needsDateFormatting()); + $this->assertEquals(array('created_at', 'deleted_at'), $set->getDateColumns()); + } + + public function testSetSeparator() + { + $set = $this->loadedCsv->setSeperator('-'); + $this->assertEquals('-', $set->getSeperator()); + } + + public function testSetDelimiter() + { + $set = $this->loadedCsv->setDelimiter(';'); + $this->assertEquals(';', $set->getDelimiter()); + } + + public function testCalculate() + { + $set = $this->loadedCsv->calculate(); + $this->assertTrue($set->needsCalculation()); + } + + public function testIgnoreEmpty() + { + $set = $this->loadedCsv->ignoreEmpty(); + $this->assertTrue($set->needsIgnoreEmpty()); + } + + /** + * Load a csv file + * @return [type] [description] + */ + protected function loadCsv() + { + // Set test csv file + $this->csvFile = __DIR__ . '/' . 'test.csv'; + + // Loaded csv + $this->loadedCsv = $this->reader->load($this->csvFile); + } + +} \ No newline at end of file diff --git a/tests/Readers/ReaderTest.php b/tests/Readers/ReaderTest.php new file mode 100644 index 000000000..3a9fde456 --- /dev/null +++ b/tests/Readers/ReaderTest.php @@ -0,0 +1,33 @@ +excel = App::make('phpexcel'); + + // Set writer class + $this->reader = App::make('excel.reader'); + $this->reader->injectExcel($this->excel); + } + + /** + * Test the excel injection + * @return [type] [description] + */ + public function testExcelInjection() + { + $this->assertEquals($this->excel, $this->reader->getExcel()); + } + +} \ No newline at end of file diff --git a/tests/Readers/test.csv b/tests/Readers/test.csv new file mode 100644 index 000000000..919af7248 --- /dev/null +++ b/tests/Readers/test.csv @@ -0,0 +1,6 @@ +heading1,heading2,heading3 +test,test,test +test,test,test +test,test,test +test,test,test +test,test,test \ No newline at end of file diff --git a/tests/Writers/ExcelWriterTest.php b/tests/Writers/ExcelWriterTest.php index fd60b1021..e58650f3f 100644 --- a/tests/Writers/ExcelWriterTest.php +++ b/tests/Writers/ExcelWriterTest.php @@ -22,6 +22,15 @@ public function setUp() } + /** + * Test the excel injection + * @return [type] [description] + */ + public function testExcelInjection() + { + $this->assertEquals($this->excel, $this->writer->getExcel()); + } + /** * Test setTitle() * @return [type] [description] From 47b75d92c1a17a909f600c9cbfc0c7febb57f214 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 12 Jun 2014 21:06:46 +0200 Subject: [PATCH 0173/1332] Added ->getTitle() for sheets and workbook, fixes issue #145 --- README.md | 2 +- docs/changelog/version-1.md | 4 +++ docs/import/results.md | 13 +++++++++ .../Excel/Collections/ExcelCollection.php | 28 ++++++++++++++++++- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 7 +++-- 5 files changed, 49 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 517e2c2e6..a1231ea10 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.1.0 +## Laravel Excel v1.1.1 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index e77651d7e..1e7580e18 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.1.1 + +- Retrieve workbook and sheet title during import (`->getTitle()`) + ### 1.1.0 - `Limit()`, `skip()` and `take()` support for fetching results diff --git a/docs/import/results.md b/docs/import/results.md index 20557c09f..e51a02963 100644 --- a/docs/import/results.md +++ b/docs/import/results.md @@ -37,6 +37,19 @@ To get the first sheet or row, you can utilise `->first()`. > **Note:** depending on the config `'force_sheets_collection'` it will return the first row or sheet. +### Workbook and sheet title + +It's possible to retrieve the workbook and sheet title with `->getTitle()`. + + // Get workbook title + $workbookTitle = $reader->getTitle(); + + foreach($reader as $sheet) + { + // get sheet title + $sheetTitle = $sheet->getTitle(); + } + ### Limiting the results ##### Taking rows diff --git a/src/Maatwebsite/Excel/Collections/ExcelCollection.php b/src/Maatwebsite/Excel/Collections/ExcelCollection.php index f679c28d6..1ab24756d 100644 --- a/src/Maatwebsite/Excel/Collections/ExcelCollection.php +++ b/src/Maatwebsite/Excel/Collections/ExcelCollection.php @@ -13,4 +13,30 @@ * @author Maatwebsite * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class ExcelCollection extends Collection {} \ No newline at end of file +class ExcelCollection extends Collection { + + /** + * Sheet title + * @var [type] + */ + protected $title; + + /** + * Get the title + * @return [type] [description] + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set the title + * @param [type] $title [description] + */ + public function setTitle($title) + { + $this->title = $title; + } + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index fc8e53249..ff4fe5b01 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -125,6 +125,7 @@ public function parseFile($columns = array()) { // Push every sheet $workbook->push($worksheet); + $workbook->setTitle($this->excel->getProperties()->getTitle()); } else { @@ -160,9 +161,6 @@ protected function parseWorksheet() // Set the active worksheet $this->excel->setActiveSheetIndex($this->w); - // Get the worksheet name - $title = $this->excel->getActiveSheet()->getTitle(); - // Fetch the labels $this->indices = $this->reader->hasHeading() ? $this->getIndices() : array(); @@ -209,6 +207,9 @@ protected function parseRows() // Set empty parsedRow array $parsedRows = new RowCollection(); + // set sheet title + $parsedRows->setTitle($this->excel->getActiveSheet()->getTitle()); + // Get the startrow $startRow = $this->getStartRow(); From 9f6950d08f4ef91511d8899624114235616384a0 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 12 Jun 2014 21:12:53 +0200 Subject: [PATCH 0174/1332] Namespace fix --- src/Maatwebsite/Excel/Excel.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 9a718786d..236bf5a89 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -1,8 +1,8 @@ Date: Sun, 15 Jun 2014 13:44:23 +0200 Subject: [PATCH 0175/1332] Multiple options to convert import table headings (slugged, ascii, numeric, hashed, orignal, trans), fixes issue #150 --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 128 ++++++++++++++++-- .../Excel/Readers/LaravelExcelReader.php | 5 +- src/config/import.php | 6 +- 3 files changed, 128 insertions(+), 11 deletions(-) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index ff4fe5b01..1b93e125e 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -93,6 +93,9 @@ public function __construct($reader) { $this->reader = $reader; $this->excel = $reader->excel; + + // Reset + $this->reset(); } /** @@ -183,21 +186,119 @@ protected function getIndices() // Loop through the cells foreach ($this->row->getCellIterator() as $this->cell) { - // Set labels - if(Config::get('excel::import.to_ascii', true)) - { - $this->indices[] = Str::slug($this->cell->getValue(), $this->reader->getSeperator()); - } - else - { - $this->indices[] = strtolower(str_replace(array(' '), $this->reader->getSeperator(), $this->cell->getValue())); - } + var_dump($this->getIndex($this->cell)); + $this->indices[] = $this->getIndex($this->cell); } // Return the labels return $this->indices; } + /** + * Get index + * @param $cell + * @return string + */ + protected function getIndex($cell) + { + // Get heading type + $config = Config::get('excel::import.heading', true); + $config = $config === true ? 'slugged' : $config; + + // Get value + $value = $this->getOriginalIndex($cell); + + switch($config) + { + case 'slugged': + return $this->getSluggedIndex($value, Config::get('excel::import.to_ascii', true)); + break; + + case 'ascii': + return $this->getAsciiIndex($value); + break; + + case 'hashed': + return $this->getHashedIndex($value); + break; + + case 'trans': + return $this->getTranslatedIndex($value); + break; + + case 'original': + return $value; + break; + } + } + + /** + * Get slugged index + * @param string $value + * @return string + */ + protected function getSluggedIndex($value, $ascii = false) + { + // Get original + $separator = $this->reader->getSeperator(); + + // Convert to ascii when needed + if($ascii) + $value = $this->getAsciiIndex($value); + + // Convert all dashes/underscores into separator + $flip = $separator == '-' ? '_' : '-'; + $value = preg_replace('!['.preg_quote($flip).']+!u', $separator, $value); + + // Remove all characters that are not the separator, letters, numbers, or whitespace. + $value = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($value)); + + // Replace all separator characters and whitespace by a single separator + $value = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $value); + + return trim($value, $separator); + } + + /** + * Get ASCII index + * @param string $value + * @return string + */ + protected function getAsciiIndex($value) + { + return Str::ascii($value); + } + + /** + * Hahsed index + * @param string $value + * @return string + */ + protected function getHashedIndex($value) + { + return md5($value); + } + + /** + * Get translated index + * @param string $value + * @return string + */ + protected function getTranslatedIndex($value) + { + return trans($value); + } + + /** + * Get orignal indice + * @param string $value + * @return string + */ + protected function getOriginalIndex($cell) + { + return $cell->getValue(); + } + /** * Parse the rows * @return RowCollection @@ -480,4 +581,13 @@ protected function getSelectedColumns() } + /** + * Reset + * @return [type] [description] + */ + protected function reset() + { + $this->indices = array(); + } + } diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index b9c4082c1..e6347ea85 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -539,7 +539,10 @@ public function ignoreEmpty($boolean = true) public function hasHeading() { if(!$this->noHeading) - return Config::get('excel::import.heading', true); + { + $config = Config::get('excel::import.heading', true); + return $config !== false && $config !== 'numeric'; + } return $this->noHeading ? false : true; } diff --git a/src/config/import.php b/src/config/import.php index 17a8149cb..eabb3778e 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -9,9 +9,11 @@ | | The sheet has a heading (first) row which we can use as attribute names | + | Options: true|false|slugged|ascii|numeric|hashed|trans|original + | */ - 'heading' => true, + 'heading' => 'slugged', /* |-------------------------------------------------------------------------- @@ -19,6 +21,7 @@ |-------------------------------------------------------------------------- | | The default seperator which is used for the cell names + | Note: only applies to 'heading' settings 'true' && 'slugged' | */ @@ -30,6 +33,7 @@ |-------------------------------------------------------------------------- | | Convert headings to ASCII + | Note: only applies to 'heading' settings 'true' && 'slugged' | */ From 002c4e090e6dcd4d0c78f8a1bc4665508c178ba3 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 15 Jun 2014 13:58:14 +0200 Subject: [PATCH 0176/1332] Clone reader|writer instances to prevent getting old settings when calling create()|load() multiple times, fixes issue #149 --- src/Maatwebsite/Excel/Excel.php | 22 ++++++++++++------- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 +- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 236bf5a89..7a293e974 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -60,6 +60,9 @@ public function __construct(PHPExcel $excel, LaravelExcelReader $reader, Laravel */ public function create($title, $callback = null) { + // Writer instance + $writer = clone $this->writer; + // Set the default properties $this->excel->setDefaultProperties(array( 'title' => $title @@ -69,17 +72,17 @@ public function create($title, $callback = null) $this->excel->disconnectWorksheets(); // Inject our excel object - $this->writer->injectExcel($this->excel); + $writer->injectExcel($this->excel); // Set the title - $this->writer->setTitle($title); + $writer->setTitle($title); // Do the callback if($callback instanceof Closure) - call_user_func($callback, $this->writer); + call_user_func($callback, $writer); // Return the writer object - return $this->writer; + return $writer; } /** @@ -94,21 +97,24 @@ public function create($title, $callback = null) */ public function load($file, $callback = null, $encoding = null) { + // Reader instance + $reader = clone $this->reader; + // Inject excel object - $this->reader->injectExcel($this->excel); + $reader->injectExcel($this->excel); // Set the encoding $encoding = is_string($callback) ? $callback : $encoding; // Start loading - $this->reader->load($file, $encoding); + $reader->load($file, $encoding); // Do the callback if($callback instanceof Closure) - call_user_func($callback, $this->reader); + call_user_func($callback, $reader); // Return the reader object - return $this->reader; + return $reader; } /** diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 1b93e125e..2d23c708a 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -186,7 +186,6 @@ protected function getIndices() // Loop through the cells foreach ($this->row->getCellIterator() as $this->cell) { - var_dump($this->getIndex($this->cell)); $this->indices[] = $this->getIndex($this->cell); } @@ -588,6 +587,7 @@ protected function getSelectedColumns() protected function reset() { $this->indices = array(); + $this->isParsed = false; } } From 819ba221272ab15257806f4f5a758d65eed0935b Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 15 Jun 2014 14:06:12 +0200 Subject: [PATCH 0177/1332] Update docs about import heading conversion --- README.md | 2 +- docs/changelog/version-1.md | 5 +++++ docs/import/results.md | 11 +++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a1231ea10..db602239c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.1.1 +## Laravel Excel v1.1.2 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 1e7580e18..b5e66c0b3 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,10 @@ # Version 1 +### 1.1.2 + +- Fix for multiple imports on one pageload +- Multiple new import heading conversions (Config: excel::import.heading: true|false|slugged|ascii|numeric|hashed|trans|original) + ### 1.1.1 - Retrieve workbook and sheet title during import (`->getTitle()`) diff --git a/docs/import/results.md b/docs/import/results.md index e51a02963..c2fa8c795 100644 --- a/docs/import/results.md +++ b/docs/import/results.md @@ -22,6 +22,17 @@ or > The `->get()` and `->all()` methods will return a sheet or row collection, depending on the amount of sheets the file has. You can disable this feature inside the `import.php` config by setting `'force_sheets_collection'` to `true`. When set to true it will always return a sheet collection. +### Table heading as attributes + +By default the first row of the excel file will be used as attributes. + + // Get the firstname + $row->firstname; + +> **Note**: by default these attributes will be converted to a slug. You can change the default inside the config `excel::import.heading`. Available options are: `true|false|slugged|ascii|numeric|hashed|trans|original` + +> True and slugged will be converted to ASCII as well when `excel::import.to_ascii` is set to true. You can change the default separator as well inside the config. + ### Collections Sheets, rows and cells are collections, this means after doing a `->get()` you can use all default collection methods. From d8cef3339f92548e3769534a536dc913ab3b387c Mon Sep 17 00:00:00 2001 From: tlshaheen Date: Tue, 17 Jun 2014 12:27:01 -0400 Subject: [PATCH 0178/1332] Modified setBorder() in CellWriter.php Modified setBorder() so that 'top', 'left', etc. are moved up one position in the array that is passed to setStyle. --- src/Maatwebsite/Excel/Writers/CellWriter.php | 26 +++++++++----------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/src/Maatwebsite/Excel/Writers/CellWriter.php b/src/Maatwebsite/Excel/Writers/CellWriter.php index 6db0bedbc..646b960a3 100644 --- a/src/Maatwebsite/Excel/Writers/CellWriter.php +++ b/src/Maatwebsite/Excel/Writers/CellWriter.php @@ -135,19 +135,17 @@ public function setBorder($top = 'none', $right = 'none', $bottom = 'none', $lef { // Set the border styles $styles = is_array($top) ? $top : array( - 'borders' => array( - 'top' => array( - 'style' => $top - ), - 'left' => array( - 'style' => $left, - ), - 'right' => array( - 'style' => $right, - ), - 'bottom' => array( - 'style' => $bottom, - ) + 'top' => array( + 'style' => $top + ), + 'left' => array( + 'style' => $left, + ), + 'right' => array( + 'style' => $right, + ), + 'bottom' => array( + 'style' => $bottom, ) ); @@ -225,4 +223,4 @@ protected function getCellStyle() return $this->sheet->getStyle($this->cells); } -} \ No newline at end of file +} From 5d50bcdaf293aa1a39bb1c71f3561a23ddf9af10 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Tue, 17 Jun 2014 23:14:51 +0200 Subject: [PATCH 0179/1332] Update changelog --- README.md | 2 +- docs/changelog/version-1.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index db602239c..c7cc8e0a8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.1.2 +## Laravel Excel v1.1.3 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index b5e66c0b3..731fb9945 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.1.3 + +- Cell writer `->setBorder()` fix + ### 1.1.2 - Fix for multiple imports on one pageload From 3fbb36532ea2bf7cb02a76fc00a4b597cf627330 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 19 Jun 2014 11:56:22 +0200 Subject: [PATCH 0180/1332] Added unit test for chinese xls files import --- tests/Readers/ChineseXlsReaderTest.php | 100 +++++++++++++++++++++++++ tests/Readers/CsvReaderTest.php | 2 +- tests/Readers/files/chinese.xls | Bin 0 -> 20480 bytes tests/Readers/{ => files}/test.csv | 0 4 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 tests/Readers/ChineseXlsReaderTest.php create mode 100644 tests/Readers/files/chinese.xls rename tests/Readers/{ => files}/test.csv (100%) diff --git a/tests/Readers/ChineseXlsReaderTest.php b/tests/Readers/ChineseXlsReaderTest.php new file mode 100644 index 000000000..3dbcda6ff --- /dev/null +++ b/tests/Readers/ChineseXlsReaderTest.php @@ -0,0 +1,100 @@ +excel = App::make('phpexcel'); + + // Set writer class + $this->reader = App::make('excel.reader'); + $this->reader->injectExcel($this->excel); + + // Load csv file + $this->loadChineseXls(); + } + + /** + * Test loading a csv file + * @return [type] [description] + */ + public function testloadChineseXls() + { + $this->assertEquals($this->reader, $this->loadedXls); + $this->assertInstanceOf('PHPExcel', $this->reader->getExcel()); + } + + /** + * Test get + * @return [type] [description] + */ + public function testGet() + { + $got = $this->loadedXls->get(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); + $this->assertCount(2, $got); + } + + + /** + * Test toArray + * @return [type] [description] + */ + public function testToArray() + { + $array = $this->loadedXls->toArray(); + $this->assertEquals(array( + + array( + '商品編號' => 'L01A01SY047', + '商品名稱' => 'LED T8燈管', + '實際數量' => '1', + ), + array( + '商品編號' => 'L01A01SY046', + '商品名稱' => 'LED T8燈管', + '實際數量' => '1', + ) + + ), $array); + } + + /** + * Load a csv file + * @return [type] [description] + */ + protected function loadChineseXls() + { + // Set test csv file + $this->xls = __DIR__ . '/files/' . 'chinese.xls'; + + // Loaded csv + $this->loadedXls = $this->reader->load($this->xls); + } + +} \ No newline at end of file diff --git a/tests/Readers/CsvReaderTest.php b/tests/Readers/CsvReaderTest.php index 427c772f1..cb840f415 100644 --- a/tests/Readers/CsvReaderTest.php +++ b/tests/Readers/CsvReaderTest.php @@ -300,7 +300,7 @@ public function testIgnoreEmpty() protected function loadCsv() { // Set test csv file - $this->csvFile = __DIR__ . '/' . 'test.csv'; + $this->csvFile = __DIR__ . '/files/' . 'test.csv'; // Loaded csv $this->loadedCsv = $this->reader->load($this->csvFile); diff --git a/tests/Readers/files/chinese.xls b/tests/Readers/files/chinese.xls new file mode 100644 index 0000000000000000000000000000000000000000..6857d49d8cd6c653dfbb793d192ceff6b11f6e7f GIT binary patch literal 20480 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 literal 0 HcmV?d00001 diff --git a/tests/Readers/test.csv b/tests/Readers/files/test.csv similarity index 100% rename from tests/Readers/test.csv rename to tests/Readers/files/test.csv From f8de5de4b88430a16d28cacc88a0ffa2199ea2e1 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 22 Jun 2014 14:31:32 +0200 Subject: [PATCH 0181/1332] Fix for importing 0 as null, fixes issue #153 --- src/Maatwebsite/Excel/Collections/CellCollection.php | 2 +- tests/Readers/ChineseXlsReaderTest.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/Collections/CellCollection.php b/src/Maatwebsite/Excel/Collections/CellCollection.php index c26b3ec4d..aa0e3e48c 100644 --- a/src/Maatwebsite/Excel/Collections/CellCollection.php +++ b/src/Maatwebsite/Excel/Collections/CellCollection.php @@ -46,7 +46,7 @@ public function setItems($items) foreach($items as $name => $value) { if($name) - $this->put($name, $value ? $value : null); + $this->put($name, $value || is_numeric($value) ? $value : null); } } diff --git a/tests/Readers/ChineseXlsReaderTest.php b/tests/Readers/ChineseXlsReaderTest.php index 3dbcda6ff..c608c1a20 100644 --- a/tests/Readers/ChineseXlsReaderTest.php +++ b/tests/Readers/ChineseXlsReaderTest.php @@ -73,12 +73,12 @@ public function testToArray() array( '商品編號' => 'L01A01SY047', '商品名稱' => 'LED T8燈管', - '實際數量' => '1', + '實際數量' => 1, ), array( '商品編號' => 'L01A01SY046', '商品名稱' => 'LED T8燈管', - '實際數量' => '1', + '實際數量' => 1, ) ), $array); From f50251b98bb237bd5b4fff10823cc06f4bc849e2 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 22 Jun 2014 14:42:50 +0200 Subject: [PATCH 0182/1332] Added test for import heading conversions --- tests/Readers/CsvReaderTest.php | 128 +++++++++++++++++++++++++++----- tests/Readers/files/test.csv | 2 +- 2 files changed, 111 insertions(+), 19 deletions(-) diff --git a/tests/Readers/CsvReaderTest.php b/tests/Readers/CsvReaderTest.php index cb840f415..bae3951ea 100644 --- a/tests/Readers/CsvReaderTest.php +++ b/tests/Readers/CsvReaderTest.php @@ -25,6 +25,9 @@ public function setUp() { parent::setUp(); + // Set default heading + Config::set('excel::import.heading', 'slugged'); + // Set excel class $this->excel = App::make('phpexcel'); @@ -63,7 +66,7 @@ public function testGet() */ public function testGetWithColumns() { - $columns = array('heading1', 'heading2'); + $columns = array('heading_one', 'heading_two'); $got = $this->loadedCsv->get($columns); $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); @@ -100,7 +103,7 @@ public function testFirst() */ public function testFirstWithColumns() { - $columns = array('heading1', 'heading2'); + $columns = array('heading_one', 'heading_two'); $first = $this->loadedCsv->first($columns); $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); @@ -132,34 +135,110 @@ public function testToArray() $this->assertEquals(array( array( - 'heading1' => 'test', - 'heading2' => 'test', - 'heading3' => 'test', + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', ), array( - 'heading1' => 'test', - 'heading2' => 'test', - 'heading3' => 'test', + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', ), array( - 'heading1' => 'test', - 'heading2' => 'test', - 'heading3' => 'test', + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', ), array( - 'heading1' => 'test', - 'heading2' => 'test', - 'heading3' => 'test', + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', ), array( - 'heading1' => 'test', - 'heading2' => 'test', - 'heading3' => 'test', + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', ) ), $array); } + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsSlugged() + { + $first = $this->loadedCsv->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + 'heading_one', + 'heading_two', + 'heading_three' + ), $keys); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsHashed() + { + Config::set('excel::import.heading', 'hashed'); + + $loaded = $this->reload(); + + $first = $loaded->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + md5('heading one'), + md5('heading two'), + md5('heading three') + ), $keys); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsNumeric() + { + Config::set('excel::import.heading', 'numeric'); + + $loaded = $this->reload(); + + $first = $loaded->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + 1, + 2, + 3 + ), $keys); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsOriginal() + { + Config::set('excel::import.heading', 'original'); + + $loaded = $this->reload(); + + $first = $loaded->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + 'heading one', + 'heading two', + 'heading three' + ), $keys); + } + /** * Test remember method * @return [type] [description] @@ -239,7 +318,7 @@ public function testLimit() */ public function testSelect() { - $columns = array('heading1', 'heading2'); + $columns = array('heading_one', 'heading_two'); $taken = $this->loadedCsv->select($columns); $this->assertEquals($columns, $taken->columns); @@ -306,4 +385,17 @@ protected function loadCsv() $this->loadedCsv = $this->reader->load($this->csvFile); } + /** + * Load a csv file + * @return [type] [description] + */ + protected function reload() + { + // Set test csv file + $this->csvFile = __DIR__ . '/files/' . 'test.csv'; + + // Loaded csv + return $this->reader->load($this->csvFile); + } + } \ No newline at end of file diff --git a/tests/Readers/files/test.csv b/tests/Readers/files/test.csv index 919af7248..9c79211a3 100644 --- a/tests/Readers/files/test.csv +++ b/tests/Readers/files/test.csv @@ -1,4 +1,4 @@ -heading1,heading2,heading3 +heading one,heading two,heading three test,test,test test,test,test test,test,test From 8ee8381df9450e0124e65a1685e768a80a6597b7 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 22 Jun 2014 14:46:10 +0200 Subject: [PATCH 0183/1332] Added test for import heading conversions --- tests/Readers/CsvReaderTest.php | 391 +------------------------------- 1 file changed, 5 insertions(+), 386 deletions(-) diff --git a/tests/Readers/CsvReaderTest.php b/tests/Readers/CsvReaderTest.php index bae3951ea..39cb77a36 100644 --- a/tests/Readers/CsvReaderTest.php +++ b/tests/Readers/CsvReaderTest.php @@ -7,395 +7,14 @@ class CsvReaderTest extends TestCase { /** - * Test csv file - * @var [type] + * Import trait */ - protected $csvFile; + use ImportTrait; /** - * Loaded csv file - * @var [type] + * Filename + * @var string */ - protected $loadedCsv; - - /** - * Setup - */ - public function setUp() - { - parent::setUp(); - - // Set default heading - Config::set('excel::import.heading', 'slugged'); - - // Set excel class - $this->excel = App::make('phpexcel'); - - // Set writer class - $this->reader = App::make('excel.reader'); - $this->reader->injectExcel($this->excel); - - // Load csv file - $this->loadCsv(); - } - - /** - * Test loading a csv file - * @return [type] [description] - */ - public function testLoadCsv() - { - $this->assertEquals($this->reader, $this->loadedCsv); - $this->assertInstanceOf('PHPExcel', $this->reader->getExcel()); - } - - /** - * Test get - * @return [type] [description] - */ - public function testGet() - { - $got = $this->loadedCsv->get(); - $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); - $this->assertCount(5, $got); - } - - /** - * Test get with columns - * @return [type] [description] - */ - public function testGetWithColumns() - { - $columns = array('heading_one', 'heading_two'); - $got = $this->loadedCsv->get($columns); - - $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); - $this->assertCount(5, $got); - } - - /** - * Test all - * @return [type] [description] - */ - public function testAll() - { - $all = $this->loadedCsv->all(); - $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $all); - $this->assertCount(5, $all); - } - - /** - * Test first - * @return [type] [description] - */ - public function testFirst() - { - $first = $this->loadedCsv->first(); - $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); - - // 3 columns - $this->assertCount(3, $first); - } - - /** - * Test first with columns - * @return [type] [description] - */ - public function testFirstWithColumns() - { - $columns = array('heading_one', 'heading_two'); - $first = $this->loadedCsv->first($columns); - - $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); - $this->assertCount(count($columns), $first); - } - - /** - * Test each - * @return [type] [description] - */ - public function testEach() - { - $me = $this; - - $this->loadedCsv->each(function($cells) use($me) { - - $me->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $cells); - - }); - } - - /** - * Test toArray - * @return [type] [description] - */ - public function testToArray() - { - $array = $this->loadedCsv->toArray(); - $this->assertEquals(array( - - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ), - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ), - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ), - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ), - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ) - - ), $array); - } - - /** - * Test the imported headings - * @return [type] [description] - */ - public function testImportedHeadingsSlugged() - { - $first = $this->loadedCsv->first()->toArray(); - $keys = array_keys($first); - - $this->assertEquals(array( - 'heading_one', - 'heading_two', - 'heading_three' - ), $keys); - } - - /** - * Test the imported headings - * @return [type] [description] - */ - public function testImportedHeadingsHashed() - { - Config::set('excel::import.heading', 'hashed'); - - $loaded = $this->reload(); - - $first = $loaded->first()->toArray(); - $keys = array_keys($first); - - $this->assertEquals(array( - md5('heading one'), - md5('heading two'), - md5('heading three') - ), $keys); - } - - /** - * Test the imported headings - * @return [type] [description] - */ - public function testImportedHeadingsNumeric() - { - Config::set('excel::import.heading', 'numeric'); - - $loaded = $this->reload(); - - $first = $loaded->first()->toArray(); - $keys = array_keys($first); - - $this->assertEquals(array( - 1, - 2, - 3 - ), $keys); - } - - /** - * Test the imported headings - * @return [type] [description] - */ - public function testImportedHeadingsOriginal() - { - Config::set('excel::import.heading', 'original'); - - $loaded = $this->reload(); - - $first = $loaded->first()->toArray(); - $keys = array_keys($first); - - $this->assertEquals(array( - 'heading one', - 'heading two', - 'heading three' - ), $keys); - } - - /** - * Test remember method - * @return [type] [description] - */ - public function testRemember() - { - $remembered = $this->loadedCsv->remember(10); - - $this->assertEquals($this->reader, $remembered); - $this->assertEquals(10, $remembered->cacheMinutes); - $this->assertTrue($remembered->remembered); - } - - /** - * Test set selected sheets - * @return [type] [description] - */ - public function testByConfig() - { - $config = $this->loadedCsv->byConfig('excel::import.sheets'); - $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); - } - - /** - * Test set selected sheets - * @return [type] [description] - */ - public function testByConfigCallback() - { - $me = $this; - - $config = $this->loadedCsv->byConfig('excel::import.sheets', function($config) use($me) - { - $me->assertInstanceOf('Maatwebsite\Excel\Readers\ConfigReader', $config); - }); - - $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); - } - - /** - * Test take - * @return [type] [description] - */ - public function testTake() - { - $taken = $this->loadedCsv->take(2); - $this->assertEquals(2, $taken->getLimit()); - $this->assertCount(2, $taken->get()); - } - - /** - * Test limit - * @return [type] [description] - */ - public function testSkip() - { - $taken = $this->loadedCsv->skip(1); - $this->assertEquals(1, $taken->getSkip()); - $this->assertCount(4, $taken->get()); - } - - /** - * Test limit - * @return [type] [description] - */ - public function testLimit() - { - $taken = $this->loadedCsv->limit(2, 1); - $this->assertEquals(2, $taken->getLimit()); - $this->assertEquals(1, $taken->getSkip()); - $this->assertCount(2, $taken->get()); - } - - /** - * Test select columns - * @return [type] [description] - */ - public function testSelect() - { - $columns = array('heading_one', 'heading_two'); - - $taken = $this->loadedCsv->select($columns); - $this->assertEquals($columns, $taken->columns); - } - - /** - * Test set date format - * @return [type] [description] - */ - public function testSetDateFormat() - { - $set = $this->loadedCsv->setDateFormat('Y-m-d'); - $this->assertEquals('Y-m-d', $set->getDateFormat()); - } - - public function testFormatDates() - { - $set = $this->loadedCsv->formatDates(true, 'Y-m-d'); - $this->assertTrue($set->needsDateFormatting()); - $this->assertEquals('Y-m-d', $set->getDateFormat()); - } - - public function testSetDateColumns() - { - $set = $this->loadedCsv->setDateColumns('created_at', 'deleted_at'); - $this->assertTrue($set->needsDateFormatting()); - $this->assertEquals(array('created_at', 'deleted_at'), $set->getDateColumns()); - } - - public function testSetSeparator() - { - $set = $this->loadedCsv->setSeperator('-'); - $this->assertEquals('-', $set->getSeperator()); - } - - public function testSetDelimiter() - { - $set = $this->loadedCsv->setDelimiter(';'); - $this->assertEquals(';', $set->getDelimiter()); - } - - public function testCalculate() - { - $set = $this->loadedCsv->calculate(); - $this->assertTrue($set->needsCalculation()); - } - - public function testIgnoreEmpty() - { - $set = $this->loadedCsv->ignoreEmpty(); - $this->assertTrue($set->needsIgnoreEmpty()); - } - - /** - * Load a csv file - * @return [type] [description] - */ - protected function loadCsv() - { - // Set test csv file - $this->csvFile = __DIR__ . '/files/' . 'test.csv'; - - // Loaded csv - $this->loadedCsv = $this->reader->load($this->csvFile); - } - - /** - * Load a csv file - * @return [type] [description] - */ - protected function reload() - { - // Set test csv file - $this->csvFile = __DIR__ . '/files/' . 'test.csv'; - - // Loaded csv - return $this->reader->load($this->csvFile); - } + protected $fileName = '/files/' . 'test.csv'; } \ No newline at end of file From 183a3a126e17cd578e3b6b6f3c7d0e89def30e21 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 22 Jun 2014 14:51:00 +0200 Subject: [PATCH 0184/1332] Move import tests to trait to use them for all import tests --- tests/Readers/CsvReaderTest.php | 4 +- tests/Readers/traits/ImportTrait.php | 396 +++++++++++++++++++++++++++ 2 files changed, 399 insertions(+), 1 deletion(-) create mode 100644 tests/Readers/traits/ImportTrait.php diff --git a/tests/Readers/CsvReaderTest.php b/tests/Readers/CsvReaderTest.php index 39cb77a36..d225eb03d 100644 --- a/tests/Readers/CsvReaderTest.php +++ b/tests/Readers/CsvReaderTest.php @@ -1,5 +1,7 @@ excel = App::make('phpexcel'); + + // Set writer class + $this->reader = App::make('excel.reader'); + $this->reader->injectExcel($this->excel); + + // Load csv file + $this->loadFile(); + } + + /** + * Test loading a csv file + * @return [type] [description] + */ + public function testLoadFile() + { + $this->assertEquals($this->reader, $this->loadedFile); + $this->assertInstanceOf('PHPExcel', $this->reader->getExcel()); + } + + /** + * Test get + * @return [type] [description] + */ + public function testGet() + { + $got = $this->loadedFile->get(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); + $this->assertCount(5, $got); + } + + /** + * Test get with columns + * @return [type] [description] + */ + public function testGetWithColumns() + { + $columns = array('heading_one', 'heading_two'); + $got = $this->loadedFile->get($columns); + + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); + $this->assertCount(5, $got); + } + + /** + * Test all + * @return [type] [description] + */ + public function testAll() + { + $all = $this->loadedFile->all(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $all); + $this->assertCount(5, $all); + } + + /** + * Test first + * @return [type] [description] + */ + public function testFirst() + { + $first = $this->loadedFile->first(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); + + // 3 columns + $this->assertCount(3, $first); + } + + /** + * Test first with columns + * @return [type] [description] + */ + public function testFirstWithColumns() + { + $columns = array('heading_one', 'heading_two'); + $first = $this->loadedFile->first($columns); + + $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); + $this->assertCount(count($columns), $first); + } + + /** + * Test each + * @return [type] [description] + */ + public function testEach() + { + $me = $this; + + $this->loadedFile->each(function($cells) use($me) { + + $me->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $cells); + + }); + } + + /** + * Test toArray + * @return [type] [description] + */ + public function testToArray() + { + $array = $this->loadedFile->toArray(); + $this->assertEquals(array( + + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ), + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ), + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ), + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ), + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ) + + ), $array); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsSlugged() + { + $first = $this->loadedFile->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + 'heading_one', + 'heading_two', + 'heading_three' + ), $keys); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsHashed() + { + Config::set('excel::import.heading', 'hashed'); + + $loaded = $this->reload(); + + $first = $loaded->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + md5('heading one'), + md5('heading two'), + md5('heading three') + ), $keys); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsNumeric() + { + Config::set('excel::import.heading', 'numeric'); + + $loaded = $this->reload(); + + $first = $loaded->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + 1, + 2, + 3 + ), $keys); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsOriginal() + { + Config::set('excel::import.heading', 'original'); + + $loaded = $this->reload(); + + $first = $loaded->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + 'heading one', + 'heading two', + 'heading three' + ), $keys); + } + + /** + * Test remember method + * @return [type] [description] + */ + public function testRemember() + { + $remembered = $this->loadedFile->remember(10); + + $this->assertEquals($this->reader, $remembered); + $this->assertEquals(10, $remembered->cacheMinutes); + $this->assertTrue($remembered->remembered); + } + + /** + * Test set selected sheets + * @return [type] [description] + */ + public function testByConfig() + { + $config = $this->loadedFile->byConfig('excel::import.sheets'); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); + } + + /** + * Test set selected sheets + * @return [type] [description] + */ + public function testByConfigCallback() + { + $me = $this; + + $config = $this->loadedFile->byConfig('excel::import.sheets', function($config) use($me) + { + $me->assertInstanceOf('Maatwebsite\Excel\Readers\ConfigReader', $config); + }); + + $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); + } + + /** + * Test take + * @return [type] [description] + */ + public function testTake() + { + $taken = $this->loadedFile->take(2); + $this->assertEquals(2, $taken->getLimit()); + $this->assertCount(2, $taken->get()); + } + + /** + * Test limit + * @return [type] [description] + */ + public function testSkip() + { + $taken = $this->loadedFile->skip(1); + $this->assertEquals(1, $taken->getSkip()); + $this->assertCount(4, $taken->get()); + } + + /** + * Test limit + * @return [type] [description] + */ + public function testLimit() + { + $taken = $this->loadedFile->limit(2, 1); + $this->assertEquals(2, $taken->getLimit()); + $this->assertEquals(1, $taken->getSkip()); + $this->assertCount(2, $taken->get()); + } + + /** + * Test select columns + * @return [type] [description] + */ + public function testSelect() + { + $columns = array('heading_one', 'heading_two'); + + $taken = $this->loadedFile->select($columns); + $this->assertEquals($columns, $taken->columns); + } + + /** + * Test set date format + * @return [type] [description] + */ + public function testSetDateFormat() + { + $set = $this->loadedFile->setDateFormat('Y-m-d'); + $this->assertEquals('Y-m-d', $set->getDateFormat()); + } + + public function testFormatDates() + { + $set = $this->loadedFile->formatDates(true, 'Y-m-d'); + $this->assertTrue($set->needsDateFormatting()); + $this->assertEquals('Y-m-d', $set->getDateFormat()); + } + + public function testSetDateColumns() + { + $set = $this->loadedFile->setDateColumns('created_at', 'deleted_at'); + $this->assertTrue($set->needsDateFormatting()); + $this->assertEquals(array('created_at', 'deleted_at'), $set->getDateColumns()); + } + + public function testSetSeparator() + { + $set = $this->loadedFile->setSeperator('-'); + $this->assertEquals('-', $set->getSeperator()); + } + + public function testSetDelimiter() + { + $set = $this->loadedFile->setDelimiter(';'); + $this->assertEquals(';', $set->getDelimiter()); + } + + public function testCalculate() + { + $set = $this->loadedFile->calculate(); + $this->assertTrue($set->needsCalculation()); + } + + public function testIgnoreEmpty() + { + $set = $this->loadedFile->ignoreEmpty(); + $this->assertTrue($set->needsIgnoreEmpty()); + } + + /** + * Load a csv file + * @return [type] [description] + */ + protected function loadFile() + { + // Set test csv file + $this->file = __DIR__ . '/..' . DIRECTORY_SEPARATOR . $this->fileName; + + // Loaded csv + $this->loadedFile = $this->reader->load($this->file); + } + + /** + * Load a csv file + * @return [type] [description] + */ + protected function reload() + { + // Set test csv file + $this->file = __DIR__ . '/..' . DIRECTORY_SEPARATOR . $this->fileName; + + // Loaded csv + return $this->reader->load($this->file); + } +} \ No newline at end of file From 5ac9c5f44f76a903dc3f71a699efc7a5aa37f248 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 22 Jun 2014 14:56:30 +0200 Subject: [PATCH 0185/1332] Added xls and xlsx import tests --- tests/Readers/CsvReaderTest.php | 12 ++++++++++++ tests/Readers/XlsReaderTest.php | 22 ++++++++++++++++++++++ tests/Readers/XlsxReaderTest.php | 22 ++++++++++++++++++++++ tests/Readers/files/test.xls | Bin 0 -> 32256 bytes tests/Readers/files/test.xlsx | Bin 0 -> 33758 bytes tests/Readers/traits/ImportTrait.php | 12 ------------ 6 files changed, 56 insertions(+), 12 deletions(-) create mode 100644 tests/Readers/XlsReaderTest.php create mode 100644 tests/Readers/XlsxReaderTest.php create mode 100644 tests/Readers/files/test.xls create mode 100644 tests/Readers/files/test.xlsx diff --git a/tests/Readers/CsvReaderTest.php b/tests/Readers/CsvReaderTest.php index d225eb03d..c1c8a04e9 100644 --- a/tests/Readers/CsvReaderTest.php +++ b/tests/Readers/CsvReaderTest.php @@ -19,4 +19,16 @@ class CsvReaderTest extends TestCase { */ protected $fileName = 'files/test.csv'; + public function testSetSeparator() + { + $set = $this->loadedFile->setSeperator('-'); + $this->assertEquals('-', $set->getSeperator()); + } + + public function testSetDelimiter() + { + $set = $this->loadedFile->setDelimiter(';'); + $this->assertEquals(';', $set->getDelimiter()); + } + } \ No newline at end of file diff --git a/tests/Readers/XlsReaderTest.php b/tests/Readers/XlsReaderTest.php new file mode 100644 index 000000000..636b49ed1 --- /dev/null +++ b/tests/Readers/XlsReaderTest.php @@ -0,0 +1,22 @@ +MIsZKA#|h(u@x^$s1QX< zZAFEkNbOt2T4Ik_idt%yQq1pp?wvc!oh|vlzu*6*pZCVObI-Zwe4pn$&vTx$&NzLl zNzIDQt#1(46-apGz1)JBsikw^83T1$6XFIB7=JI9%jrZy;PJoLMmCt>sleV>wf z?w#%IQyh1Q?o~LF!9+}QNhTQqpJMo|@70uWIcT>G4|OSz9KIV$=QJe)$rv&U{*r)? z@uVNgCaDxpm?9+^@SJS`)CuTgRj~aa4+gR-UwOdO1Z*U5nUdZ>A(`Sq1eB!pkeWYuxkiP{VTCtfaSvs&1nmmt~LF2zcxa233eQ+n_CWOyO4z~4}Bx!C&a;6|8 zS3D+9lq(VZUtS>;4@n&4Apq_iQVJr<_QckY z{nHChFDl=^sJk89IpD$YzMU#_nM(Hnuk-}+^T}M443}&&=Y)aj9{2RZ;e#Y#C7Y%1o~@z zIog}}fM;q&ICkVmfgLyi0d&yL5bTLNNrX7X0L6?ibj1^u4pB@!C6gK-$c9H|42hS5k5!a*6RB+yldd<^A4-g;7U)Woo( zP-*$%y%&|Iy@@jngJ3|E=+aeS?`&`Hp6Jq3`TQCEZ0BM}rS?j6X>T$SbQNfrNp&F_ zVpUal{R{^|+tX&+8^&xfLr^m6>aM{zL{+Q@1u@LmP@_mfUdjdFTbOIF0MpSiQ|T}2 zmX7XGSAKozh^j09KRKNPrmMWTw48AcK*?dN;*H5yl>D{RH|a@VrYBt=&RRYB_2K_m z&;0uM*{BCcAO039KhAM9<@2qc^rd>zX@0bE7V62rSx-7GA8njp^yHtfCtV*uEA`~p z#}8d!oGWU|X9I* zqzm8?s?SPi(Z#tnm0u|zTE8&%W^g`-N0?62I5;2I4|hk&YR-u)bhJ&85)SGyOv&7>jVV3t*Od6+pjVuL3x!t5*S>iPozCy3~3VK%La9 z02*z*3ZPQzRRGPrUInmy)vEwHlzJ7wmQk+)*!1dE0NYZ%3ZV0=SAlNzEr82o^`d}l zY4s|A3vcx*fGcnHDuBy$ssh;l)SUn)pC8Qf8n~9iQ+f?{0WM$RPOxDLVCatX7;O+- zKr{*>4>AmbE09J(JiRnQ*iO(JK=juioFKdY?nyf zP#|}QsVYvbQ0)kSX>_&ippR3f(Q}zzu(GX6b0OwitNt~?JD<;H3fGX;nF`X))U#*L zw3rGC3esW<)7VU58k;Fh)6WzxjH{S>ldnhIx|sUklN8$;aphfQ16oWmYLORml#6mxG?me?YXS3dwOXJZXoxnSKZw;Ham&O+>0Y&JfpSMBsXH}w zm&>$AZNFs)rBvP$BHBu318alez*q&M#U09+M?|UW+-Za0LcCFs$_T?CxV5DMfrzf^ zu$@1<_1M=1gx;dl@5^yArQ$@dOmN_-9|U*rjDl1~7zV+uJ{1T=bj!prh(ldK=q*eA z)xn90iW9vu!LhY|5Zk(dR7MyEX|DkS5#2H|4B}W95cEEVs)Li?I>^K@2=4A01*wcM z3$yt0PLq8Ipbw-0e0BQW;?wM4$lz5#2H|4AQwS zAoLc${_5c3lF{mjQgITf9|U**je=B07zXL60Rj=-GEoPa&ut1jmoT~WbaxcE2!fN7 zMcGo1dHhH+4@IZAI414o4T&dgDmX$NTp$F)j%+gQQQ&?oJ;UI@eu}w?DD~={r*cz# z=1_&@j<_~~WSX$acxsceGeCx(gHU8lMXArOUeQgaDVvO!HknQa$k4MCij0{k^}*9> z-DH}v$#`p%>1u!s&SQ9lB4aK}y?yZ5TUrMo<6Q?!tBlxDd0RJ`mTWRQEY02k8Ffpm zjJUI7yKXYJY%)45t+N3#>Xud+aq;$U-DFy^$>^}OZU)GxTUupA<=)G>$+TvZ(P3$B z2FR#eT4luc>U+A$v|*FcVQF3l$f#RdWyIU_TXmCZi)4Bjwlo2d=}`wu^YmJ<Xzo|^=8i;U1Y3a zlN-ie%6>DL)o-?wo9pc>35lLqp&Qg*1qv3$2JOfKRktG8`iP0t4eFo*1^Z!xIjv$t0tHK8 zgL<$))wNGZ?ZPl!pnN!i36t=Uq?CDlKTXYZ+Q@k%1eP09ls&L1E{ebkA&!pl8J7_i zp2Ql?FTfgpXi`@4n5-mehB$j3f1)NJw}rd`p$}Z)VYn=SRvo@Gr$!P8ipyCH0bE|9 z2$;cnE_{jW85|IUdW^3Tv(Sjm=Qf5VQP_SG|KCK9}2t>$nB1eR&~jLXSN%1)AsbH@u}MdPIN_@8P*al6Z{ zNgpx}jvAuwvnl=K(a`ZA^H^YK9M}UcUNPE7Wh>0f0_q0KGoOmZV5mJcaXGE!Cgf8P znwVv(xFXJA0Wk)v5sdd?2GLiPl#-F1CV;sDi&366NVYF9gtngnjHUsD^c;aQ0cbEC z`sLGbXo}{*8SMz?a~r`VLk%2!9~-=h4shE4=>eAqt=@xUcm(%S2L~U>25+hZoc4oy z!0Dj@mjd@z2M1rsatOR;I>6B%(i$^Y7t4IEC7jcSb)SCOIb*;S#%QXHYXkMcbGSKR zi>P!}LzBb0Kch6<9QZezzcmbyz%NB)WM_&}6z#u1iy2$+OA(Z!GePMo8XkbBv__>b zV!RJ7ahrkQtl%U%^q^6qG1A;5a4#&!%xMdbISPQWrnz8K=ve3(4dqW^vxKQ{DeR~y z3?59XkU(?v(&UvxfMgU{dM zwMLxvP^`d0HRIB7ky+(v=@{eE=osVD=-7O212~8ei(1iRq?E?!VRCv=SAgpM(s&@ptFpA?#c>>M;%Ff|25#6X>Ml@osy8JcQOG}YJ)X%zDo+-!7Nw0jNGWR%+gJoR9pkPGdK@mjjvDt6+OglF@IklAXBBy*v5P2evU zKt@ot9SAIsr=B9A?&u8hAiW<*F@ubyEJ$|_Z!!;#mE-;h(1H{5*Z5|n!*&~pog;6b zo04bz$%L%GPmm%>!S(F9WbWus;JXB?!0rpl-o1O_qmU%8drz*pcoO-`StRP_V3O8E zPTsE$BU1+sCf`-eHTs@Z%Hbb|O5me}lt5fwQc1wa5O6faD^*UsDk~u!_{2~GA(fES z)Dp6A;X?S%Nh|(wxS*#{<%z_uRRq{QY)Bm3JZWg@Zz%itK96kg>ZrE{2738Z@%ZCKt zf(bWO;DEbJSM+VtJTc57m9g|(kx1>WI9mjCku^CCk@(~Z>>YuXk%jz)Rtwb#KoW`R z&oi-s_KnFM$&!0H(Qo0YEzoWTpTk1M*-}_{ON*sGf zKWmQt%B$uMYqti@-kbZcr52xWKfU5-ml-{i13a3h`H#Q1bHe@>V|nZE7Wpsh+k4~r zTWiHL)_G5M_if<3JaygTEjy=&?i5@d_&!2smL58M<(kujqiMGeJ&Y#nHYkARU(K&4x?sG zVXdlKeRnUs=>hr!>6642zHL?0BjUH0Erb_*KHoTJ%`y3w1MZdIM(-=wjh>Y7KR;+QmHLzmt z8qvCQ?N68QcwO}ls-j)d%<&6b6hQ@NK)~HHX}V~X$W84Y3FE^wQ7)Q?Rb`~*0fBX| z8~H2p=3eqi-sRM1MA`9;yIzsd($>L8mY-dA<-+f`ihNF9w>iJ0f5V~9rREK1h)%dp z-~MER^XfKhF86JF$T{oAk>+>)7-xHI>%W>^?{`!(Am9G{+$kH%uL-KkyPfa&*!fz* z&kiF4W_~*O-fy*CZuWW5t&=6!S2y$Sji+Zefo{AS_Ox2)V%`JUemFE*+@_Ds9{Z>5 z!erv)&SP7DI%eI)&BM}v3)?*G+^ul|ucEwmZCTu^^V5dqpE@}74*qQJj?uk(t%|!T z42)dPpK)%}-X$g1UPk$6mp1LyOOjr(Wl!y$itB%S6}-A%erwT+P&T=jZMG~pA1=ywJnU@|GbuSnmgfCk$Kd=8o)>>z zkZ0@PDg6G#xnF%77unXLs9pQm?jcd4B^J`@L%j;ePkp;4diJ0~+l7`1-bFKBH;CJ| zabwMii0Nxh%N&2+`1<&5&xtqott%Ng%ly#F^Vu6li&mc&lZX?yK3N*IYoN=ER-{qr zlXI7aRYMXk z7FY#_2KTVJv}(2O)7~z>mfHr^eAj?9Oc`>|5gmPF2lnA}941Ka6p@ zJN3n9eWyP}Q+x7XzU}hG%eTjl9Z2ikxWIS(i+i_k)W&^dKaSV= zR$0yQO+l~U9dCR_9KGj@*ME5hB`kazR8V^+I_S&$<{_phoWFSbdVb=!0pp(@I z=NEa`Ta1gDTALB!urqS@>A*Srd_res`n8(=yx$A^h;|ljCuYyNKYK>onnzty13#O& z?r~N1FeK6mA_J)eS5jHO?CwR?hSL1s3$3s)TDO~c!#-<0}_49lc?b=CnHSqAX zUw*#gJ38b_$;#8+pRbhe5Py2mLo(+^?;9TdriZ*~7bG}%>so$zyM(+9ryaNLr~Ena z-2QX@`z>o!+Iz9ZwdEcMMfab#3VD>XMb^07_xbpW&_=@@Y)n$y-}-y9pLfEMW>b=v z{TeuXXvvddL;3{T%LX=CIJ(_h!P(^fzW1%ZDh@2^$$jf$`mWQ|FMn_Nx9gI_u0p3T zYJMBvK#~yl=aZtblW(1y_UMd5*W~N-&F6k+`)KsnPjov)_( zOxh)VxX8P|^}AF%|INFjcFf;X(WOn&h@DnjrK<-X@g6_?N~+D9ZA)*Ax{_^n<)`Vd zXWTu!HnoCZ>y~w<=eT(fo2;4f+VTFVXwx8?$aR2g!Uelt4Z4aL1e|bNAszuwYLq4}JG8x<| z(*3_wv`%+SE?L{Ye{rtG-9BCq&u@78Q|;haTZdk_YkkGfA#T@%^l2Af74EQ z!*?QGTCq_5C+ph9x%=7Hz;%SF^-`Hd^;7<7%hy9@=LT_7rbMeQ;7k}^KeRtW| zQ+JNOzUVxJclKnD{VNaMd^>dB?a%hjO0o7I9_ifWLW};V2Y98Q8~lJ{Ir_3ySkBog z%SKxU&;P=0`X$?qGeaD+s=ggM^M}4^?S0-39W>?mOjFZa#iP5fyu8n|%)@(ASg4R?g<-xA7QPwVX_IdQ zpLZ*N+ULKZl6QUgwl;T9KAy4hubH{4N)OAu2EWK9KK#tkb`z~#^Gw5b3Kw%)cD;Fe z%Gv2thjSkM@<+S5E;*qMHcgzcV?+;mgWNUp?cLMHEGnB?wEXhwWCthb&Rv^Mei%H= z^HSc_vXR?f3|ZhjFvW9S%EpKdmw35-ha}eS9doUSXA`_`N%p*QPEpUL1%FE7f{Qj+ ze_#CI#2+b#&SqrRJg(kxafI3Gs7H>{_jlg5?9^iY-&rrWJPY$rv_C%kUdt`Rg)W;c z)1GE}m#wWnJz3PE=4^as&#KZR>t9~=oqluo5%(bv(}X+BL*8^4B45KVd6%%F<+;G? z)2e6GJTLmaad2GX+2IX6`}*|#JCpp~zGwRUe(TH5rS|M_BL0^liBH1H7uDKax?Co@ znIBa)GqSkn(t$Hu_8WWnrvv5fhV|{<`<3*o{imIRrY+jLsPXXM#RDchA>0by_V>+F z_e34D`8J~6O4qf}_N-LLL);(H|3^aX`@0@w{O}hEGD=8Z;?A($2 z!;oibPQ&((3lde&KUG$Ispw`V@1;pXOsyzZ|cxLXhZSbZIj1O>YTCMMQqlZ0IirP3pF${{d-0yBPxpq<>Uo8G@r}fvJ zu1!C^;T&)B?d}bG1UU?N_^9DVXTIySq+d!hc73z-ShHl$YLE1Ft@)q)v0(J#eWP|f zoZU;J4JyU-Ae9~;O&!gsPU-x&4?BpPHa`jl0+o*H+{L<4iVqX_-^! ze+WLh>vZ4RG5O1%F5yf##x$>IAc-HO#7 z0(gL(hpW4tK$M*<#)ZZJyFsyGF1~g_ftLOqdq;=H4vpy}$jQo(NCh#2LL&Nw3hZ3m z+=6p*vP5ofy<>X|Vj}ttj1>Ten_HhKJAqxgRGRaNn_FI9o@)~3a!nSG!i*BPm|Ss= zC|5c@0>E6LfNP30#SX~O=o;)mYDz}3G|rxgABri8>n<;aZ;y*$rkg9mgn9_q`yjlnXOlJjpxx4$jQBMeLkR^#UNh%7< zN=j3*1o=UVBADX@0t)j;ap=ad=6a$H1Z}l++Qrg9zB$ok47dnpY{LWE!I(n&_(^jt%O}eZ8M=%>EfeP!+MgvyuG|! zVM|(h=`8H&?e6{2myNU;@Wm^sA3Dud5L+wWUZ}@f} zUoQ*T6NK#?CS}GII0}A?#OiL z-F-gjE}RiiPEN`{*H7!KoSLuxPtQ5oos4338ywRQRy1%kLN)4E%#z*RT|HqKTDQe_ zDIDw4LSWORdTH#j>7@xZY~{4s&2@ zNb&`28sQl~jx)y@H-oJ9ShSXx%gY;%v=H&qOl7zz;|;j0169pfXrL@Tl$nCsR^Pp*939MAb4X* z@~NYH5NpsFb|kq}oC}}ptmrs_)8lwiyK2;-MLri!?Zd@`jVn~a?XM{70G-cj3l_+x2^O2;_VuZ=S?F2s-ve21Tnp*$1AoT?b+WMYV>9#hYW zl2Ef1D0K+47nMXkwnI=e>a-{aGzm{8Y5bNXje1F!giTKTf*-Fpy;};2C_!3( z^f^=feRL#;pZ~r7`4V^!K7(h8R-k!Nc5(j1`BK+5*7LvNlWxwhH@ZWX8VL9edwd@Q z0grkNfq=glG7bXn#1}$9?=c+$9sr&T0Z&aXf&eFu$#MvIlz1luv^{G$4T3+6VGBX) zN5;c4vPMBVwo3e;2dJHXc+&UT9tb0E=+86`R}(9EgVc}`mL4q5&6K2zL{bR_t}Oz{ zWBlSkOTnW9XesR9zITA)kr~OkVu?6aD(EvVS(GL4^MT(X@N{?g7AWacZOu2VUkLI{ z<#HW}e7X7>C;xBfFr@#QDa)R{j!w5;|262p^Oj5QKrI3ki4FzD)fWQ#z!(UamIVRN znWNrOzdu4ieeZyPc5n~^9_O!wpssg3GQrk6BvG0&^bU^^tK=J*lnk>hu_T?AG`#Bt zVQ+ESbNoLC@Ok;*zHcFUMO-|sLxl5x0ow49$1McV%cAkQf^*FnqOx8OZYlu zLT!}f1-zkRTw!rsc|t9uL;QJxoEt90eDEHK$f{pKN|;BoZMYDgXuyFabJ%O~1fHzA zK%P)bgG5QfJn|}N5V!-Vu$X#-yhA}*b(qI96(lcQSRjv*$f|1@(7}-LjaX)apfoJd z`kyMV_Yvrv5=v%);0Bz`BwGO^5K7FIh-g1G`7qYSYEekVh$g~eeWneoD6 zeB*aAzAB;CV^+XpYRdZI}nwe4qa@)%x>TAUV$kK#ywm);ZwMF0m4^$l zna~x%mK0)*n!-}pvallWq9lz_6HyY>16IC3j?|EXSf){lW3(o?X@2olvT87&!Pu}1 z&XOdJe4sB>}A# z(jca&9yS;{j$Rz@3j~6jzQiM@Nd!P#jVd zYB7a=7he@Fq*F8F(L#mAD6=%bfX6K8VG2%Bpfotz4w`#re26tZ(=gbk=~T3#gjzaP zRxK<>|A%To_2>adtV#Uc4DBYN7N2PtbRCjXG(9wURVu20NsX^!fjfenXl76THlf$G236M&H55LdspLE~G1j=7*I* zbH!)6Lg*5(Ldbr6RhS2zigLviSv9s}zmu#AF{(gs#Ha#2k>AO1A&OiqqhYWu_?^VY zjB-r2rBe|!#2Vc}xDbi3z=zY7)R3Vn3D#S9DD!Kpws(`XZ!(fcG(81BtqPyn!DwGdC(~M)Q zz{V_=q2ps(g;*Bw7_ALcb+n2^ppE@fUIn^#s-02|4Ap^+3|)@8IszVJvqM6f>cE_| zC9vehv}me#18BORL0^jf8)HUD9!EB5e%KQ+W>g?YH;t)CP^(4PNfoVMrul*R??_6O z_oI?h7|?<6?KK(}qfwSF84ri-f%su8q3z)?4SgPdf-ld*jq;V`z(csa35mzNXEba^@KDY5g?!#nn5v?XHihz=8bD12s` z5RMzr(_w$b7z#e2CuCAt;8dGoS_`|)Q0j64b%B(*vTB6}>eg;l4j*NX7AUL6cEa$5 z&$4Qof9&h&I!H>fPo`6GOvU1sX*ZHm9K$f}2D@h3jV09LGYy3V0v=yVvc1_zCG5J8># zeY&%udVHNe%nKYoGteL6@Df(bdu~17b_o!6>5P(YAC?2ZwG9nanT9VkW70B^!)IJy*D8~YMn1|5UC&P!Nlok;7ct)95H#Hn+*TFhfbm)!@ z$C^gz)X8oHI_*X=qoIZb3~iikqY>cr#3*g`I?^j*^(umMj?8$YMHtp3r8oe`=2Qpq zW50wwQXTBy5f&_8!HiF9$fVh>coP8*e?tGi*MD9D9L2B1<-pqU2r{zX4B`L8Dp$Me X0)R{5BkGc|j(OC`|3|FqW2XN<8W!|d literal 0 HcmV?d00001 diff --git a/tests/Readers/files/test.xlsx b/tests/Readers/files/test.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..56faa7ce75fd6d630f66ef6b476f5208cd666034 GIT binary patch literal 33758 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 literal 0 HcmV?d00001 diff --git a/tests/Readers/traits/ImportTrait.php b/tests/Readers/traits/ImportTrait.php index 2931d2fd9..498dd05f5 100644 --- a/tests/Readers/traits/ImportTrait.php +++ b/tests/Readers/traits/ImportTrait.php @@ -344,18 +344,6 @@ public function testSetDateColumns() $this->assertEquals(array('created_at', 'deleted_at'), $set->getDateColumns()); } - public function testSetSeparator() - { - $set = $this->loadedFile->setSeperator('-'); - $this->assertEquals('-', $set->getSeperator()); - } - - public function testSetDelimiter() - { - $set = $this->loadedFile->setDelimiter(';'); - $this->assertEquals(';', $set->getDelimiter()); - } - public function testCalculate() { $set = $this->loadedFile->calculate(); From 725df730bab83397a631574a63731bb6c410ade1 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sun, 22 Jun 2014 15:01:25 +0200 Subject: [PATCH 0186/1332] Readme + changelog version update --- README.md | 2 +- docs/changelog/version-1.md | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c7cc8e0a8..cd1df03b5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.1.3 +## Laravel Excel v1.1.4 [](http://www.maatwebsite.nl/laravel-excel/docs) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 731fb9945..ed389d15a 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,10 @@ # Version 1 +### 1.1.4 + +- Fix for importing 0 as null +- New unit tests + ### 1.1.3 - Cell writer `->setBorder()` fix @@ -7,7 +12,7 @@ ### 1.1.2 - Fix for multiple imports on one pageload -- Multiple new import heading conversions (Config: excel::import.heading: true|false|slugged|ascii|numeric|hashed|trans|original) +- Multiple new import heading conversions (`Config: excel::import.heading: true|false|slugged|ascii|numeric|hashed|trans|original`) ### 1.1.1 From 228f0bff5dd587c60ef4063f16ccee9c60492be1 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 2 Jul 2014 21:20:30 +0200 Subject: [PATCH 0187/1332] Select sheets by index, fixes issue #165 --- src/Maatwebsite/Excel/Excel.php | 17 +- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 43 ++- .../Excel/Readers/LaravelExcelReader.php | 37 ++ tests/Excel/ExcelTestCase.php | 7 +- tests/Excel/ExcelTester.php | 19 +- tests/Readers/CsvReaderTest.php | 3 +- tests/Readers/MultipleSheetsXlsReaderTest.php | 111 ++++++ tests/Readers/XlsReaderTest.php | 3 +- tests/Readers/XlsxReaderTest.php | 3 +- tests/Readers/files/multiple.xls | Bin 0 -> 33280 bytes tests/Readers/traits/ImportTrait.php | 311 ----------------- .../traits/SingleImportTestingTrait.php | 315 ++++++++++++++++++ 12 files changed, 525 insertions(+), 344 deletions(-) create mode 100644 tests/Readers/MultipleSheetsXlsReaderTest.php create mode 100644 tests/Readers/files/multiple.xls create mode 100644 tests/Readers/traits/SingleImportTestingTrait.php diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 7a293e974..536904656 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -122,9 +122,22 @@ public function load($file, $callback = null, $encoding = null) * @param $sheets * @return LaravelExcelReader */ - public function selectSheets($sheets) + public function selectSheets($sheets = array()) { - $this->reader->setSelectedSheets(is_array($sheets) ? $sheets : array($sheets)); + $sheets = is_array($sheets) ? $sheets : func_get_args(); + $this->reader->setSelectedSheets($sheets); + return $this; + } + + /** + * Select sheets by index + * @param [type] $sheets [description] + * @return [type] [description] + */ + public function selectSheetsByIndex($sheets = array()) + { + $sheets = is_array($sheets) ? $sheets : func_get_args(); + $this->reader->setSelectedSheetIndices($sheets); return $this; } diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 2d23c708a..209baff5b 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -117,25 +117,33 @@ public function parseFile($columns = array()) // Set worksheet count $this->w = 0; + // Get selected sheets + $iterator = $this->excel->getWorksheetIterator(); + // Loop through the worksheets - foreach($this->excel->getWorksheetIterator() as $this->worksheet) + foreach($iterator as $this->worksheet) { - // Parse the worksheet - $worksheet = $this->parseWorksheet(); - - // If multiple sheets - if($this->parseAsMultiple()) + // Check if the sheet might have been selected by it's index + if($this->reader->isSelectedByIndex($iterator->key() )) { - // Push every sheet - $workbook->push($worksheet); - $workbook->setTitle($this->excel->getProperties()->getTitle()); - } - else - { - // Ignore the sheet collection - $workbook = $worksheet; - break; + // Parse the worksheet + $worksheet = $this->parseWorksheet(); + + // If multiple sheets + if($this->parseAsMultiple()) + { + // Push every sheet + $workbook->push($worksheet); + $workbook->setTitle($this->excel->getProperties()->getTitle()); + } + else + { + // Ignore the sheet collection + $workbook = $worksheet; + break; + } } + $this->w++; } } @@ -152,7 +160,8 @@ public function parseFile($columns = array()) */ protected function parseAsMultiple() { - return $this->excel->getSheetCount() > 1 || Config::get('excel::import.force_sheets_collection', false); + return ( $this->excel->getSheetCount() > 1 && count($this->reader->getSelectedSheetIndices()) !== 1 ) + || Config::get('excel::import.force_sheets_collection', false); } /** @@ -590,4 +599,4 @@ protected function reset() $this->isParsed = false; } -} +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index e6347ea85..dfa470e57 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -153,6 +153,12 @@ class LaravelExcelReader { */ public $selectedSheets = array(); + /** + * Selected sheet indices + * @var array + */ + public $selectedSheetIndices = array(); + /** * Construct new reader * @param FileSystem $files @@ -204,6 +210,37 @@ public function sheetsSelected() return count($this->selectedSheets) > 0; } + /** + * Check if the file was selected by index + * @param [type] $index [description] + * @return boolean [description] + */ + public function isSelectedByIndex($index) + { + $selectedSheets = $this->getSelectedSheetIndices(); + if(empty($selectedSheets)) return true; + return in_array($index, $selectedSheets) ? true : false; + } + + /** + * Set the selected sheet indices + * @param [type] $sheets [description] + */ + public function setSelectedSheetIndices($sheets) + { + $this->selectedSheetIndices = $sheets; + return $this; + } + + /** + * Return the selected sheets + * @return [type] [description] + */ + public function getSelectedSheetIndices() + { + return $this->selectedSheetIndices; + } + /** * Remember the results for x minutes * @param integer $minutes diff --git a/tests/Excel/ExcelTestCase.php b/tests/Excel/ExcelTestCase.php index c050f06b2..5731e288a 100644 --- a/tests/Excel/ExcelTestCase.php +++ b/tests/Excel/ExcelTestCase.php @@ -72,6 +72,7 @@ public function mockReader() $this->reader->shouldReceive('injectExcel')->with($this->phpexcel); $this->reader->shouldReceive('load'); $this->reader->shouldReceive('setSelectedSheets'); + $this->reader->shouldReceive('setSelectedSheetIndices'); } /** @@ -105,4 +106,8 @@ public function tearDown() m::close(); } -} \ No newline at end of file +} + + + + diff --git a/tests/Excel/ExcelTester.php b/tests/Excel/ExcelTester.php index 972c0b588..e4779d77f 100644 --- a/tests/Excel/ExcelTester.php +++ b/tests/Excel/ExcelTester.php @@ -34,16 +34,15 @@ public function testSelectSheets() $this->assertEquals($this->excel, $selected); } - // /** - // * Test a batch - // * @return [type] [description] - // */ - // public function testBatch() - // { - // $batch = $this->excel->batch(); - // $loaded = $batch->start($this->excel, array('file'), function() {}); - // $this->assertInstanceOf('Maatwebsite\Excel\Readers\Batch', $loaded); - // } + /** + * Test select sheets + * @return [type] [description] + */ + public function testSelectSheetsByIndex() + { + $selected = $this->excel->selectSheetsByIndex(array('0')); + $this->assertEquals($this->excel, $selected); + } /** * Test the share view diff --git a/tests/Readers/CsvReaderTest.php b/tests/Readers/CsvReaderTest.php index c1c8a04e9..d8f0bf3a9 100644 --- a/tests/Readers/CsvReaderTest.php +++ b/tests/Readers/CsvReaderTest.php @@ -1,6 +1,7 @@ loadedFile->get(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $got); + $this->assertCount(2, $got); + } + + /** + * Test get + * @return [type] [description] + */ + public function testGetAndGetFirstSheetName() + { + $got = $this->loadedFile->get(); + + // get first sheet + $sheet = $got->first(); + + // assert sheet title + $this->assertEquals('Sheet1', $sheet->getTitle()); + + // 5 rows + $this->assertCount(5, $sheet); + } + + public function testSelectSheet() + { + $this->reader->setSelectedSheets('Sheet2'); + $this->reload(); + + $sheet = $this->loadedFile->get(); + + $this->assertEquals('Sheet2', $sheet->getTitle()); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $sheet); + $this->assertCount(5, $sheet); + } + + public function testSelectSheetByIndex() + { + $this->reader->setSelectedSheetIndices(array(1)); + $this->reload(); + + $sheet = $this->loadedFile->get(); + + $this->assertEquals('Sheet2', $sheet->getTitle()); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $sheet); + $this->assertCount(5, $sheet); + } + + public function testSelectMultipleSheets() + { + $this->reader->setSelectedSheets(array('Sheet1', 'Sheet2')); + $this->reload(); + + $got = $this->loadedFile->get(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $got); + $this->assertCount(2, $got); + + // get first sheet + $sheet = $got->first(); + + // assert sheet title + $this->assertEquals('Sheet1', $sheet->getTitle()); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $sheet); + $this->assertCount(5, $sheet); + } + + public function testSelectMultipleSheetsByIndex() + { + $this->reader->setSelectedSheetIndices(array(0,1)); + $this->reload(); + + $got = $this->loadedFile->get(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $got); + $this->assertCount(2, $got); + + // get first sheet + $sheet = $got->first(); + + // assert sheet title + $this->assertEquals('Sheet1', $sheet->getTitle()); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $sheet); + $this->assertCount(5, $sheet); + } + +} \ No newline at end of file diff --git a/tests/Readers/XlsReaderTest.php b/tests/Readers/XlsReaderTest.php index 636b49ed1..afb883cd9 100644 --- a/tests/Readers/XlsReaderTest.php +++ b/tests/Readers/XlsReaderTest.php @@ -1,6 +1,7 @@ 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 I51Ib|0z_d3X#fBK literal 0 HcmV?d00001 diff --git a/tests/Readers/traits/ImportTrait.php b/tests/Readers/traits/ImportTrait.php index 498dd05f5..1156d5976 100644 --- a/tests/Readers/traits/ImportTrait.php +++ b/tests/Readers/traits/ImportTrait.php @@ -45,317 +45,6 @@ public function testLoadFile() $this->assertInstanceOf('PHPExcel', $this->reader->getExcel()); } - /** - * Test get - * @return [type] [description] - */ - public function testGet() - { - $got = $this->loadedFile->get(); - $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); - $this->assertCount(5, $got); - } - - /** - * Test get with columns - * @return [type] [description] - */ - public function testGetWithColumns() - { - $columns = array('heading_one', 'heading_two'); - $got = $this->loadedFile->get($columns); - - $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); - $this->assertCount(5, $got); - } - - /** - * Test all - * @return [type] [description] - */ - public function testAll() - { - $all = $this->loadedFile->all(); - $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $all); - $this->assertCount(5, $all); - } - - /** - * Test first - * @return [type] [description] - */ - public function testFirst() - { - $first = $this->loadedFile->first(); - $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); - - // 3 columns - $this->assertCount(3, $first); - } - - /** - * Test first with columns - * @return [type] [description] - */ - public function testFirstWithColumns() - { - $columns = array('heading_one', 'heading_two'); - $first = $this->loadedFile->first($columns); - - $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); - $this->assertCount(count($columns), $first); - } - - /** - * Test each - * @return [type] [description] - */ - public function testEach() - { - $me = $this; - - $this->loadedFile->each(function($cells) use($me) { - - $me->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $cells); - - }); - } - - /** - * Test toArray - * @return [type] [description] - */ - public function testToArray() - { - $array = $this->loadedFile->toArray(); - $this->assertEquals(array( - - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ), - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ), - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ), - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ), - array( - 'heading_one' => 'test', - 'heading_two' => 'test', - 'heading_three' => 'test', - ) - - ), $array); - } - - /** - * Test the imported headings - * @return [type] [description] - */ - public function testImportedHeadingsSlugged() - { - $first = $this->loadedFile->first()->toArray(); - $keys = array_keys($first); - - $this->assertEquals(array( - 'heading_one', - 'heading_two', - 'heading_three' - ), $keys); - } - - /** - * Test the imported headings - * @return [type] [description] - */ - public function testImportedHeadingsHashed() - { - Config::set('excel::import.heading', 'hashed'); - - $loaded = $this->reload(); - - $first = $loaded->first()->toArray(); - $keys = array_keys($first); - - $this->assertEquals(array( - md5('heading one'), - md5('heading two'), - md5('heading three') - ), $keys); - } - - /** - * Test the imported headings - * @return [type] [description] - */ - public function testImportedHeadingsNumeric() - { - Config::set('excel::import.heading', 'numeric'); - - $loaded = $this->reload(); - - $first = $loaded->first()->toArray(); - $keys = array_keys($first); - - $this->assertEquals(array( - 1, - 2, - 3 - ), $keys); - } - - /** - * Test the imported headings - * @return [type] [description] - */ - public function testImportedHeadingsOriginal() - { - Config::set('excel::import.heading', 'original'); - - $loaded = $this->reload(); - - $first = $loaded->first()->toArray(); - $keys = array_keys($first); - - $this->assertEquals(array( - 'heading one', - 'heading two', - 'heading three' - ), $keys); - } - - /** - * Test remember method - * @return [type] [description] - */ - public function testRemember() - { - $remembered = $this->loadedFile->remember(10); - - $this->assertEquals($this->reader, $remembered); - $this->assertEquals(10, $remembered->cacheMinutes); - $this->assertTrue($remembered->remembered); - } - - /** - * Test set selected sheets - * @return [type] [description] - */ - public function testByConfig() - { - $config = $this->loadedFile->byConfig('excel::import.sheets'); - $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); - } - - /** - * Test set selected sheets - * @return [type] [description] - */ - public function testByConfigCallback() - { - $me = $this; - - $config = $this->loadedFile->byConfig('excel::import.sheets', function($config) use($me) - { - $me->assertInstanceOf('Maatwebsite\Excel\Readers\ConfigReader', $config); - }); - - $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); - } - - /** - * Test take - * @return [type] [description] - */ - public function testTake() - { - $taken = $this->loadedFile->take(2); - $this->assertEquals(2, $taken->getLimit()); - $this->assertCount(2, $taken->get()); - } - - /** - * Test limit - * @return [type] [description] - */ - public function testSkip() - { - $taken = $this->loadedFile->skip(1); - $this->assertEquals(1, $taken->getSkip()); - $this->assertCount(4, $taken->get()); - } - - /** - * Test limit - * @return [type] [description] - */ - public function testLimit() - { - $taken = $this->loadedFile->limit(2, 1); - $this->assertEquals(2, $taken->getLimit()); - $this->assertEquals(1, $taken->getSkip()); - $this->assertCount(2, $taken->get()); - } - - /** - * Test select columns - * @return [type] [description] - */ - public function testSelect() - { - $columns = array('heading_one', 'heading_two'); - - $taken = $this->loadedFile->select($columns); - $this->assertEquals($columns, $taken->columns); - } - - /** - * Test set date format - * @return [type] [description] - */ - public function testSetDateFormat() - { - $set = $this->loadedFile->setDateFormat('Y-m-d'); - $this->assertEquals('Y-m-d', $set->getDateFormat()); - } - - public function testFormatDates() - { - $set = $this->loadedFile->formatDates(true, 'Y-m-d'); - $this->assertTrue($set->needsDateFormatting()); - $this->assertEquals('Y-m-d', $set->getDateFormat()); - } - - public function testSetDateColumns() - { - $set = $this->loadedFile->setDateColumns('created_at', 'deleted_at'); - $this->assertTrue($set->needsDateFormatting()); - $this->assertEquals(array('created_at', 'deleted_at'), $set->getDateColumns()); - } - - public function testCalculate() - { - $set = $this->loadedFile->calculate(); - $this->assertTrue($set->needsCalculation()); - } - - public function testIgnoreEmpty() - { - $set = $this->loadedFile->ignoreEmpty(); - $this->assertTrue($set->needsIgnoreEmpty()); - } - /** * Load a csv file * @return [type] [description] diff --git a/tests/Readers/traits/SingleImportTestingTrait.php b/tests/Readers/traits/SingleImportTestingTrait.php new file mode 100644 index 000000000..c132d910f --- /dev/null +++ b/tests/Readers/traits/SingleImportTestingTrait.php @@ -0,0 +1,315 @@ +loadedFile->get(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); + $this->assertCount(5, $got); + } + + /** + * Test get with columns + * @return [type] [description] + */ + public function testGetWithColumns() + { + $columns = array('heading_one', 'heading_two'); + $got = $this->loadedFile->get($columns); + + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $got); + $this->assertCount(5, $got); + } + + /** + * Test all + * @return [type] [description] + */ + public function testAll() + { + $all = $this->loadedFile->all(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\RowCollection', $all); + $this->assertCount(5, $all); + } + + /** + * Test first + * @return [type] [description] + */ + public function testFirst() + { + $first = $this->loadedFile->first(); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); + + // 3 columns + $this->assertCount(3, $first); + } + + /** + * Test first with columns + * @return [type] [description] + */ + public function testFirstWithColumns() + { + $columns = array('heading_one', 'heading_two'); + $first = $this->loadedFile->first($columns); + + $this->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $first); + $this->assertCount(count($columns), $first); + } + + /** + * Test each + * @return [type] [description] + */ + public function testEach() + { + $me = $this; + + $this->loadedFile->each(function($cells) use($me) { + + $me->assertInstanceOf('Maatwebsite\Excel\Collections\CellCollection', $cells); + + }); + } + + /** + * Test toArray + * @return [type] [description] + */ + public function testToArray() + { + $array = $this->loadedFile->toArray(); + $this->assertEquals(array( + + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ), + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ), + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ), + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ), + array( + 'heading_one' => 'test', + 'heading_two' => 'test', + 'heading_three' => 'test', + ) + + ), $array); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsSlugged() + { + $first = $this->loadedFile->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + 'heading_one', + 'heading_two', + 'heading_three' + ), $keys); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsHashed() + { + Config::set('excel::import.heading', 'hashed'); + + $loaded = $this->reload(); + + $first = $loaded->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + md5('heading one'), + md5('heading two'), + md5('heading three') + ), $keys); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsNumeric() + { + Config::set('excel::import.heading', 'numeric'); + + $loaded = $this->reload(); + + $first = $loaded->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + 1, + 2, + 3 + ), $keys); + } + + /** + * Test the imported headings + * @return [type] [description] + */ + public function testImportedHeadingsOriginal() + { + Config::set('excel::import.heading', 'original'); + + $loaded = $this->reload(); + + $first = $loaded->first()->toArray(); + $keys = array_keys($first); + + $this->assertEquals(array( + 'heading one', + 'heading two', + 'heading three' + ), $keys); + } + + /** + * Test remember method + * @return [type] [description] + */ + public function testRemember() + { + $remembered = $this->loadedFile->remember(10); + + $this->assertEquals($this->reader, $remembered); + $this->assertEquals(10, $remembered->cacheMinutes); + $this->assertTrue($remembered->remembered); + } + + /** + * Test set selected sheets + * @return [type] [description] + */ + public function testByConfig() + { + $config = $this->loadedFile->byConfig('excel::import.sheets'); + $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); + } + + /** + * Test set selected sheets + * @return [type] [description] + */ + public function testByConfigCallback() + { + $me = $this; + + $config = $this->loadedFile->byConfig('excel::import.sheets', function($config) use($me) + { + $me->assertInstanceOf('Maatwebsite\Excel\Readers\ConfigReader', $config); + }); + + $this->assertInstanceOf('Maatwebsite\Excel\Collections\SheetCollection', $config); + } + + /** + * Test take + * @return [type] [description] + */ + public function testTake() + { + $taken = $this->loadedFile->take(2); + $this->assertEquals(2, $taken->getLimit()); + $this->assertCount(2, $taken->get()); + } + + /** + * Test limit + * @return [type] [description] + */ + public function testSkip() + { + $taken = $this->loadedFile->skip(1); + $this->assertEquals(1, $taken->getSkip()); + $this->assertCount(4, $taken->get()); + } + + /** + * Test limit + * @return [type] [description] + */ + public function testLimit() + { + $taken = $this->loadedFile->limit(2, 1); + $this->assertEquals(2, $taken->getLimit()); + $this->assertEquals(1, $taken->getSkip()); + $this->assertCount(2, $taken->get()); + } + + /** + * Test select columns + * @return [type] [description] + */ + public function testSelect() + { + $columns = array('heading_one', 'heading_two'); + + $taken = $this->loadedFile->select($columns); + $this->assertEquals($columns, $taken->columns); + } + + /** + * Test set date format + * @return [type] [description] + */ + public function testSetDateFormat() + { + $set = $this->loadedFile->setDateFormat('Y-m-d'); + $this->assertEquals('Y-m-d', $set->getDateFormat()); + } + + public function testFormatDates() + { + $set = $this->loadedFile->formatDates(true, 'Y-m-d'); + $this->assertTrue($set->needsDateFormatting()); + $this->assertEquals('Y-m-d', $set->getDateFormat()); + } + + public function testSetDateColumns() + { + $set = $this->loadedFile->setDateColumns('created_at', 'deleted_at'); + $this->assertTrue($set->needsDateFormatting()); + $this->assertEquals(array('created_at', 'deleted_at'), $set->getDateColumns()); + } + + public function testCalculate() + { + $set = $this->loadedFile->calculate(); + $this->assertTrue($set->needsCalculation()); + } + + public function testIgnoreEmpty() + { + $set = $this->loadedFile->ignoreEmpty(); + $this->assertTrue($set->needsIgnoreEmpty()); + } +} \ No newline at end of file From ccee07e276661d3af89e6d1a372b75dd214c7861 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 2 Jul 2014 21:23:06 +0200 Subject: [PATCH 0188/1332] Update docs about selectSheetsByIndex() --- docs/changelog/version-1.md | 4 ++++ docs/import/select.md | 10 +++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index ed389d15a..89115ccfb 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,9 @@ # Version 1 +### 1.1.5 + +- Select sheets by index with `Excel::selectSheetsByIndex(0,1)->load(...)` + ### 1.1.4 - Fix for importing 0 as null diff --git a/docs/import/select.md b/docs/import/select.md index cce3bd5dc..738ce20e3 100644 --- a/docs/import/select.md +++ b/docs/import/select.md @@ -8,7 +8,15 @@ If you want to select a single sheet, you can use `->selectSheets($name)`. Only ### Selecting multiple sheets If you want to select multiple sheets inside your file, you can pass an array as the parameter; - Excel::selectSheets(array('sheet1', 'sheet2'))->load(); + Excel::selectSheets('sheet1', 'sheet2')->load(); + +### Selecting sheets by index + + // First sheet + Excel::selectSheetsByIndex(0)->load(); + + // First and second sheet + Excel::selectSheetsByIndex(0, 1)->load(); ### Selecting columns From 20d7484d36809331cd10254e60d31fa393dccd99 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 2 Jul 2014 21:50:17 +0200 Subject: [PATCH 0189/1332] Separator typo fix + fallback, fixes issue #160 --- docs/changelog/version-1.md | 1 + docs/import/extra.md | 6 ++-- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 +- .../Excel/Readers/LaravelExcelReader.php | 31 ++++++++++++------- tests/Readers/CsvReaderTest.php | 10 ++++-- 5 files changed, 32 insertions(+), 18 deletions(-) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 89115ccfb..c0f91927e 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -3,6 +3,7 @@ ### 1.1.5 - Select sheets by index with `Excel::selectSheetsByIndex(0,1)->load(...)` +- Separator typo fix ### 1.1.4 diff --git a/docs/import/extra.md b/docs/import/extra.md index ae341999c..6ad4630c8 100644 --- a/docs/import/extra.md +++ b/docs/import/extra.md @@ -9,14 +9,14 @@ To disable this for a single import, use `->noHeading()`. $reader->noHeading(); -### Setting the cell name seperator +### Setting the cell name separator By default collection attribute names will be set by looking at the first row columns. Spaces will be translated to `_`. **E.g. Created at -> created_at** -The default behaviour can be changed inside the `import.php` config by changing `'seperator'`. Or you can use `->setSeperator($seperator)`. +The default behaviour can be changed inside the `import.php` config by changing `'separator'`. Or you can use `->setSeparator($separator)`. - $reader->setSeperator('-'); + $reader->setSeparator('-'); ### Ignoring empty cells By default empty cells will not be ignored and presented as null inside the cell collection. diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 209baff5b..affc849f6 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -248,7 +248,7 @@ protected function getIndex($cell) protected function getSluggedIndex($value, $ascii = false) { // Get original - $separator = $this->reader->getSeperator(); + $separator = $this->reader->getSeparator(); // Convert to ascii when needed if($ascii) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index dfa470e57..3214b3a27 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -100,10 +100,10 @@ class LaravelExcelReader { protected $skip = 0; /** - * Slug seperator + * Slug separator * @var string */ - public $seperator = false; + public $separator = false; /** * Ignore empty cells @@ -525,16 +525,25 @@ public function noHeading($boolean = true) } /** - * Set the cell name word seperator - * @param string $seperator + * Set the cell name word separator + * @param string $separator * @return LaraveExcelReader */ - public function setSeperator($seperator) + public function setSeparator($separator) { - $this->seperator = $seperator; + $this->separator = $separator; return $this; } + /** + * Spelling mistake backwards compatibility + * @param [type] $separator [description] + */ + public function setSeperator($separator) + { + return $this->setSeparator($separator); + } + /** * Set the delimiter * Calling this after the ->load() will have no effect @@ -585,15 +594,15 @@ public function hasHeading() } /** - * Get the seperator + * Get the separator * @return string */ - public function getSeperator() + public function getSeparator() { - if($this->seperator) - return $this->seperator; + if($this->separator) + return $this->separator; - return Config::get('excel::import.seperator', '_'); + return Config::get('excel::import.separator', Config::get('excel::import.seperator', '_')); } /** diff --git a/tests/Readers/CsvReaderTest.php b/tests/Readers/CsvReaderTest.php index d8f0bf3a9..8472fd8bb 100644 --- a/tests/Readers/CsvReaderTest.php +++ b/tests/Readers/CsvReaderTest.php @@ -20,10 +20,15 @@ class CsvReaderTest extends TestCase { */ protected $fileName = 'files/test.csv'; + public function testSeparator() + { + $this->assertEquals('_', $this->loadedFile->getSeparator()); + } + public function testSetSeparator() { - $set = $this->loadedFile->setSeperator('-'); - $this->assertEquals('-', $set->getSeperator()); + $set = $this->loadedFile->setSeparator('-'); + $this->assertEquals('-', $set->getSeparator()); } public function testSetDelimiter() @@ -31,5 +36,4 @@ public function testSetDelimiter() $set = $this->loadedFile->setDelimiter(';'); $this->assertEquals(';', $set->getDelimiter()); } - } \ No newline at end of file From e8617288ec921598e3c88fc5a312b1e38a9a5aa6 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 2 Jul 2014 22:03:20 +0200 Subject: [PATCH 0190/1332] setTitle() consistency fix, added setFileName() and separate setTitle() setFileName() functionality, fixes issue #167 --- docs/changelog/version-1.md | 2 ++ src/Maatwebsite/Excel/Excel.php | 12 +++---- .../Excel/Writers/LaravelExcelWriter.php | 33 ++++++++++++++++--- tests/Writers/ExcelWriterTest.php | 15 +++++++++ 4 files changed, 50 insertions(+), 12 deletions(-) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index c0f91927e..875cad2f9 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -4,6 +4,8 @@ - Select sheets by index with `Excel::selectSheetsByIndex(0,1)->load(...)` - Separator typo fix +- Added `->setFileName()` method +- Use `->setTitle()` only for workbook title not for setting the filename anymore ### 1.1.4 diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 536904656..3627ed2ad 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -58,24 +58,20 @@ public function __construct(PHPExcel $excel, LaravelExcelReader $reader, Laravel * @param callable|null $callback * @return LaravelExcelWriter */ - public function create($title, $callback = null) + public function create($filename, $callback = null) { // Writer instance $writer = clone $this->writer; - // Set the default properties - $this->excel->setDefaultProperties(array( - 'title' => $title - )); - // Disconnect worksheets to prevent unnecessary ones $this->excel->disconnectWorksheets(); // Inject our excel object $writer->injectExcel($this->excel); - // Set the title - $writer->setTitle($title); + // Set the filename and title + $writer->setFileName($filename); + $writer->setTitle($filename); // Do the callback if($callback instanceof Closure) diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index b0f55e479..99e8e99c0 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -23,6 +23,12 @@ */ class LaravelExcelWriter { + /** + * Spreadsheet filename + * @var stirng + */ + public $filename; + /** * Spreadsheet title * @var stirng @@ -121,6 +127,16 @@ public function setTitle($title) return $this; } + /** + * Set the filename + * @param [type] $name [description] + */ + public function setFileName($name) + { + $this->filename = $name; + return $this; + } + /** * Get the title * @return string @@ -130,6 +146,15 @@ public function getTitle() return $this->title; } + /** + * Get the title + * @return string + */ + public function getFileName() + { + return $this->filename; + } + /** * Share view with all sheets * @param string $view @@ -252,7 +277,7 @@ protected function _download() $this->_setHeaders(array( 'Content-Type' => $this->contentType, - 'Content-Disposition' => 'attachment; filename="' . $this->title . '.' . $this->ext . '"', + 'Content-Disposition' => 'attachment; filename="' . $this->filename . '.' . $this->ext . '"', 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past 'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'), 'Cache-Control' => 'cache, must-revalidate', @@ -290,7 +315,7 @@ public function store($ext = 'xls', $path = false, $returnInfo = false) $this->_render(); // Set the storage path and file - $toStore = $this->storagePath . '/' . $this->title . '.' . $this->ext; + $toStore = $this->storagePath . '/' . $this->filename . '.' . $this->ext; // Save the file to specified location $this->writer->save($toStore); @@ -302,8 +327,8 @@ public function store($ext = 'xls', $path = false, $returnInfo = false) return array( 'full' => $toStore, 'path' => $this->storagePath, - 'file' => $this->title . '.' . $this->ext, - 'title' => $this->title, + 'file' => $this->filename . '.' . $this->ext, + 'title' => $this->filename, 'ext' => $this->ext ); diff --git a/tests/Writers/ExcelWriterTest.php b/tests/Writers/ExcelWriterTest.php index e58650f3f..c0de53abb 100644 --- a/tests/Writers/ExcelWriterTest.php +++ b/tests/Writers/ExcelWriterTest.php @@ -46,6 +46,21 @@ public function testSetTitle() $this->assertEquals($this->writer->getProperties()->getTitle(), $title); } + /** + * Test setTitle() + * @return [type] [description] + */ + public function testSetFilename() + { + $filename = 'filename'; + $filenameSet = $this->writer->setFileName($filename); + $this->assertEquals($this->writer, $filenameSet); + + // Test if title was really set + $this->assertEquals($this->writer->getFileName(), $filename); + } + + /** * Test the share view * @return [type] [description] From 6797e02d89d1b538a04022a6c7a653ed2edb94ff Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 2 Jul 2014 22:04:33 +0200 Subject: [PATCH 0191/1332] Test fix --- tests/Excel/ExcelTestCase.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Excel/ExcelTestCase.php b/tests/Excel/ExcelTestCase.php index 5731e288a..d0278aa51 100644 --- a/tests/Excel/ExcelTestCase.php +++ b/tests/Excel/ExcelTestCase.php @@ -84,6 +84,7 @@ public function mockWriter() $this->writer = m::mock('Maatwebsite\Excel\Writers\LaravelExcelWriter'); $this->writer->shouldReceive('injectExcel')->with($this->phpexcel); $this->writer->shouldReceive('setTitle'); + $this->writer->shouldReceive('setFileName'); $this->writer->shouldReceive('shareView')->andReturn($this->writer); } From 5ddce6eb9dc336e91148c44726103981455f4b93 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 2 Jul 2014 22:08:17 +0200 Subject: [PATCH 0192/1332] Made setAutoSize() chainable with other sheet methods, fixes issue #162 --- src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index d44ecbc51..c14a2d89f 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -838,6 +838,8 @@ public function setAutoSize($columns = false) // Calculate the column widths $this->calculateColumnWidths(); + + return $this; } /** From 089f864714b00d5b0a1eddfba46a8a9cf692d232 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 2 Jul 2014 22:09:12 +0200 Subject: [PATCH 0193/1332] Update changelog --- docs/changelog/version-1.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 875cad2f9..b8ad98812 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -6,6 +6,7 @@ - Separator typo fix - Added `->setFileName()` method - Use `->setTitle()` only for workbook title not for setting the filename anymore +- Made `setAutoSize()` chainable for other sheet methods ### 1.1.4 From de133357a63eea847ed8a20a483216c8b392c395 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 3 Jul 2014 16:47:01 +0200 Subject: [PATCH 0194/1332] Added config setting to disable pre formula calculation on export, involves issue #164 --- src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php | 3 +++ src/config/export.php | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 99e8e99c0..9de1252b6 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -460,6 +460,9 @@ protected function _setWriter() $this->writer->setLineEnding(Config::get('excel::csv.line_ending', "\r\n")); } + // Calculation settings + $this->writer->setPreCalculateFormulas(Config::get('excel::export.calculate', true)); + return $this->writer; } diff --git a/src/config/export.php b/src/config/export.php index c6b3c5f3f..5c1167637 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -31,6 +31,13 @@ */ 'merged_cell_alignment' => 'left', + /* + |-------------------------------------------------------------------------- + | Pre-calculate formulas during export + |-------------------------------------------------------------------------- + */ + 'calculate' => false, + /* |-------------------------------------------------------------------------- | Default sheet settings From 63a1260fc7f4eb7390e4ccb42b0c75b8faa2ba31 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 3 Jul 2014 16:52:33 +0200 Subject: [PATCH 0195/1332] Update changelog --- docs/changelog/version-1.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index b8ad98812..c93f895d8 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -7,6 +7,7 @@ - Added `->setFileName()` method - Use `->setTitle()` only for workbook title not for setting the filename anymore - Made `setAutoSize()` chainable for other sheet methods +- Export config setting to disable pre calculation of formulas during export ### 1.1.4 From 1c4366accde3d5731325770ab90741f31cde08d5 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Thu, 3 Jul 2014 17:20:48 +0200 Subject: [PATCH 0196/1332] Config setting to set autosizing method (approx|exact) + fix for autosizing view files, fixes issue #163 --- docs/changelog/version-1.md | 2 ++ .../Excel/Classes/LaravelExcelWorksheet.php | 2 +- .../Excel/ExcelServiceProvider.php | 15 ++++++++++- src/config/export.php | 26 ++++++++++++++++--- 4 files changed, 40 insertions(+), 5 deletions(-) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index c93f895d8..036ac9442 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -8,6 +8,8 @@ - Use `->setTitle()` only for workbook title not for setting the filename anymore - Made `setAutoSize()` chainable for other sheet methods - Export config setting to disable pre calculation of formulas during export +- Export config setting to set the autosizing method (approx|exact) +- Auto sizing export from view fix ### 1.1.4 diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index c14a2d89f..43e23073a 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -809,7 +809,7 @@ public function setSize($cell, $width = false, $height = false) public function setAutoSize($columns = false) { // Remember that the sheet was autosized - $this->hasFixedSizeColumns = true; + $this->hasFixedSizeColumns = $columns || !empty($columns) ? false : true; // Set autosize to true $this->autoSize = $columns ? $columns : false; diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index 1f85eb070..ce67236ff 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -2,6 +2,7 @@ use Config; use PHPExcel_Settings; +use PHPExcel_Shared_Font; use Maatwebsite\Excel\Readers\Html; use Maatwebsite\Excel\Classes\Cache; use Maatwebsite\Excel\Classes\PHPExcel; @@ -40,7 +41,11 @@ class ExcelServiceProvider extends ServiceProvider { public function boot() { + // Boot the package $this->package('maatwebsite/excel'); + + // Set the autosizing settings + $this->setAutoSizingSettings(); } /** @@ -169,6 +174,15 @@ public function setLocale() PHPExcel_Settings::setLocale($locale); } + /** + * Set the autosizing settings + */ + public function setAutoSizingSettings() + { + $method = Config::get('excel::export.autosize-method', PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX); + PHPExcel_Shared_Font::setAutoSizeMethod($method); + } + /** * Get the services provided by the provider. * @@ -185,5 +199,4 @@ public function provides() 'excel.writer' ); } - } \ No newline at end of file diff --git a/src/config/export.php b/src/config/export.php index 5c1167637..7621af6ee 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -13,6 +13,29 @@ */ 'autosize' => true, + /* + |-------------------------------------------------------------------------- + | Autosize method + |-------------------------------------------------------------------------- + | + | --> PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX + | The default is based on an estimate, which does its calculation based + | on the number of characters in the cell value (applying any calculation + | and format mask, and allowing for wordwrap and rotation) and with an + | "arbitrary" adjustment based on the font (Arial, Calibri or Verdana, + | defaulting to Calibri if any other font is used) and a proportional + | djustment for the font size. + | + | --> PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT + | The second method is more accurate, based on actual style formatting as + | well (bold, italic, etc), and is calculated by generating a gd2 imagettf + | bounding box and using its dimensions to determine the size; but this + | method is significantly slower, and its accuracy is still dependent on + | having the appropriate fonts installed. + | + */ + 'autosize-method' => PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX, + /* |-------------------------------------------------------------------------- | Auto generate table heading @@ -97,7 +120,6 @@ | The path we want to save excel file to | */ - 'path' => storage_path('exports'), /* @@ -108,9 +130,7 @@ | Whether we want to return information about the stored file or not | */ - 'returnInfo' => false ) - ); \ No newline at end of file From 1c67c462d5bdf2444fb9ece585fbf8bfdfdf1b3d Mon Sep 17 00:00:00 2001 From: Brandon Zylstra Date: Thu, 10 Jul 2014 10:12:13 -0400 Subject: [PATCH 0197/1332] bump to 1.1.5 AFAIK this is intended to be considered 1.1.5. If I'm wrong please ignore this. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cd1df03b5..daa539253 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.1.4 +## Laravel Excel v1.1.5 [](http://www.maatwebsite.nl/laravel-excel/docs) From 540fd9f956ef1e4b19f7dcaec165c28806ed8d96 Mon Sep 17 00:00:00 2001 From: Brandon Zylstra Date: Fri, 11 Jul 2014 09:47:51 -0400 Subject: [PATCH 0198/1332] Excruciatingly minor fixes --- src/config/export.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/config/export.php b/src/config/export.php index 7621af6ee..9ca8e1206 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -24,7 +24,7 @@ | and format mask, and allowing for wordwrap and rotation) and with an | "arbitrary" adjustment based on the font (Arial, Calibri or Verdana, | defaulting to Calibri if any other font is used) and a proportional - | djustment for the font size. + | adjustment for the font size. | | --> PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT | The second method is more accurate, based on actual style formatting as @@ -49,7 +49,7 @@ /* |-------------------------------------------------------------------------- - | Auto set aligment on merged cells + | Auto set alignment on merged cells |-------------------------------------------------------------------------- */ 'merged_cell_alignment' => 'left', @@ -76,7 +76,7 @@ | 1) When set to false, default margins will be used | 2) It's possible to enter a single margin which will | be used for all margins. - | 3) Alternativly you can pass an array with 4 margins + | 3) Alternatively you can pass an array with 4 margins | Default order: array(top, right, bottom, left) | */ @@ -133,4 +133,4 @@ 'returnInfo' => false ) -); \ No newline at end of file +); From fb70f0ecd76604a0ed6050d5b33f93fedabe1718 Mon Sep 17 00:00:00 2001 From: Maatwebsite Date: Sat, 12 Jul 2014 16:40:45 +0200 Subject: [PATCH 0199/1332] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index daa539253..8925ca11b 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Excel::create('Laravel Excel', function($excel) { --- -[![Build Status](https://travis-ci.org/Maatwebsite/Laravel-Excel.svg?branch=develop)](https://travis-ci.org/Maatwebsite/Laravel-Excel) +[![Build Status](https://travis-ci.org/Maatwebsite/Laravel-Excel.svg?branch=master)](https://travis-ci.org/Maatwebsite/Laravel-Excel) [![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel) [![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel) [![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel) From f189a6126514053d1e5255777a36ff48e10b97ce Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 21 Jul 2014 10:02:08 +0200 Subject: [PATCH 0200/1332] Config separator right spelling --- src/config/import.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/config/import.php b/src/config/import.php index eabb3778e..c7be66db0 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -17,15 +17,15 @@ /* |-------------------------------------------------------------------------- - | Cell name word seperator + | Cell name word separator |-------------------------------------------------------------------------- | - | The default seperator which is used for the cell names + | The default separator which is used for the cell names | Note: only applies to 'heading' settings 'true' && 'slugged' | */ - 'seperator' => '_', + 'separator' => '_', /* |-------------------------------------------------------------------------- From 98ce0ccb82a2142766337eca4d7fd4741c7ba034 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 21 Jul 2014 10:54:13 +0200 Subject: [PATCH 0201/1332] Register & enable filters + default ChunkReadFilter added --- src/Maatwebsite/Excel/Excel.php | 74 +++++++++++++++++++ .../Excel/ExcelServiceProvider.php | 12 +++ .../Excel/Filters/ChunkReadFilter.php | 46 ++++++++++++ src/config/filters.php | 23 ++++++ 4 files changed, 155 insertions(+) create mode 100644 src/Maatwebsite/Excel/Filters/ChunkReadFilter.php create mode 100644 src/config/filters.php diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 3627ed2ad..96d2c5add 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -20,6 +20,16 @@ */ class Excel { + + /** + * Filter + * @var array + */ + protected $filters = array( + 'registered' => array(), + 'enabled' => array() + ); + /** * Excel object * @var PHPExcel @@ -173,6 +183,70 @@ public function loadView($view, $data = array(), $mergeData = array()) return $this->shareView($view, $data, $mergeData); } + /** + * Set filters + * @param array $filters [description] + */ + public function registerFilters($filters = array()) + { + // If enabled array key exists + if(array_key_exists('enabled', $filters)) + { + // Set registered array + $registered = $filters['registered']; + + // Filter on enabled + $this->filter($filters['enabled']); + } + else + { + $registered = $filters; + } + + // Register the filters + $this->filters['registered'] = !empty($this->filters['registered']) ? array_merge($this->filters['registered'], $registered) : $registered; + return $this; + } + + /** + * Enable certain filters + * @param string|array $filter + * @param string|false $class + * @return Excel + */ + public function filter($filter, $class = false) + { + // Add multiple filters + if(is_array($filter)) + { + $this->filters['enabled'] = !empty($this->filters['enabled']) ? array_merge($this->filters['enabled'], $filter) : $filter; + } + else + { + // Add single filter + $this->filters['enabled'][] = $filter; + + // Overrule filter class for this request + if($class) + $this->filters['registered'][$filter] = $class; + } + + // Remove duplicates + $this->filters['enabled'] = array_unique($this->filters['enabled']); + + return $this; + } + + /** + * Get register, enabled (or both) filters + * @param string|boolean $key [description] + * @return array + */ + public function getFilters($key = false) + { + return $key ? $this->filters[$key] : $this->filters; + } + /** * Dynamically call methods * @throws LaravelExcelException diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index ce67236ff..0c23459d4 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -46,6 +46,9 @@ public function boot() // Set the autosizing settings $this->setAutoSizingSettings(); + + // Register filters + $this->registerFilters(); } /** @@ -183,6 +186,15 @@ public function setAutoSizingSettings() PHPExcel_Shared_Font::setAutoSizeMethod($method); } + /** + * Register filters + * @return [type] [description] + */ + public function registerFilters() + { + app('excel')->registerFilters(Config::get('excel::filters', array())); + } + /** * Get the services provided by the provider. * diff --git a/src/Maatwebsite/Excel/Filters/ChunkReadFilter.php b/src/Maatwebsite/Excel/Filters/ChunkReadFilter.php new file mode 100644 index 000000000..da2716e8b --- /dev/null +++ b/src/Maatwebsite/Excel/Filters/ChunkReadFilter.php @@ -0,0 +1,46 @@ +_startRow = $startRow; + $this->_endRow = $startRow + $chunkSize; + } + + /** + * Read the cell + * @param string $column + * @param integer $row + * @param string $worksheetName + * @return booleaan + */ + public function readCell($column, $row, $worksheetName = '') + { + // Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow + if (($row == 1) || ($row >= $this->_startRow && $row < $this->_endRow)) { + return true; + } + return false; + } +} \ No newline at end of file diff --git a/src/config/filters.php b/src/config/filters.php new file mode 100644 index 000000000..27328ef33 --- /dev/null +++ b/src/config/filters.php @@ -0,0 +1,23 @@ + array( + 'chunk' => 'Maatwebsite\Excel\Filters\ChunkReadFilter' + ), + + /* + |-------------------------------------------------------------------------- + | Enable certain filters for every file read + |-------------------------------------------------------------------------- + */ + + 'enabled' => array() + +); \ No newline at end of file From 25295df940bfedc8fe60def91bab94b95d0244a4 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 21 Jul 2014 11:12:29 +0200 Subject: [PATCH 0202/1332] Register filter testcase --- tests/Excel/ExcelTestCase.php | 6 +- tests/Filters/RegisterFilterTestCase.php | 79 ++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 5 deletions(-) create mode 100644 tests/Filters/RegisterFilterTestCase.php diff --git a/tests/Excel/ExcelTestCase.php b/tests/Excel/ExcelTestCase.php index d0278aa51..e582c9a2c 100644 --- a/tests/Excel/ExcelTestCase.php +++ b/tests/Excel/ExcelTestCase.php @@ -107,8 +107,4 @@ public function tearDown() m::close(); } -} - - - - +} \ No newline at end of file diff --git a/tests/Filters/RegisterFilterTestCase.php b/tests/Filters/RegisterFilterTestCase.php new file mode 100644 index 000000000..ae1bf6c35 --- /dev/null +++ b/tests/Filters/RegisterFilterTestCase.php @@ -0,0 +1,79 @@ +excel = app('excel'); + } + + public function testRegisterThroughConfig() + { + $registered = Config::get('excel::filters.registered'); + + $filters = $this->excel->getFilters('registered'); + $this->assertEquals($registered, $filters); + } + + public function testOnlyRegister() + { + $toRegister = array( + 'chunk' => 'ChunkFilter' + ); + + $excel = $this->excel->registerFilters($toRegister); + + $filters = $this->excel->getFilters('registered'); + $this->assertEquals($toRegister, $filters); + } + + public function testRegisterAndEnabled() + { + $toRegister = array( + 'registered' => array( + 'chunk' => 'ChunkFilter' + ), + 'enabled' => array( + 'chunk' + ) + ); + + $excel = $this->excel->registerFilters($toRegister); + + $filters = $this->excel->getFilters(); + $this->assertEquals($toRegister, $filters); + + } + + public function testEnableOneFilter() + { + $excel = $this->excel->filter('chunk'); + + $filters = $this->excel->getFilters('enabled'); + $this->assertContains('chunk', $filters); + } + + public function testEnableMultipleFilter() + { + $excel = $this->excel->filter(array('chunk', 'range')); + + $filters = $this->excel->getFilters('enabled'); + $this->assertContains('chunk', $filters); + $this->assertContains('range', $filters); + } + + public function testEnableFilterAndOverruleFilterClass() + { + $excel = $this->excel->filter('chunk', 'ChunkFilter'); + + $registered = $this->excel->getFilters('registered'); + $this->assertEquals(array('chunk' => 'ChunkFilter'), $registered); + + $enabled = $this->excel->getFilters('enabled'); + $this->assertContains('chunk', $enabled); + + } +} \ No newline at end of file From 35b1e9dfa4ab3f9fd95f0f5052d50ee1fe6f25ee Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Mon, 21 Jul 2014 13:15:40 +0200 Subject: [PATCH 0203/1332] Implement import in chunks --- src/Maatwebsite/Excel/Excel.php | 9 +- .../Excel/Readers/LaravelExcelReader.php | 102 ++++++++++++++++++ 2 files changed, 108 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 96d2c5add..f71636d4e 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -18,8 +18,7 @@ * @author Maatwebsite * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class Excel -{ +class Excel { /** * Filter @@ -109,6 +108,9 @@ public function load($file, $callback = null, $encoding = null) // Inject excel object $reader->injectExcel($this->excel); + // Enable filters + $reader->setFilters($this->filters); + // Set the encoding $encoding = is_string($callback) ? $callback : $encoding; @@ -185,7 +187,8 @@ public function loadView($view, $data = array(), $mergeData = array()) /** * Set filters - * @param array $filters [description] + * @param array $filters + * @return Excel */ public function registerFilters($filters = array()) { diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 3214b3a27..a2a29f92e 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -159,6 +159,18 @@ class LaravelExcelReader { */ public $selectedSheetIndices = array(); + /** + * Active filter + * @var PHPExcel_Reader_IReadFilter + */ + protected $filter; + + /** + * Filters + * @var array + */ + public $filters = array(); + /** * Construct new reader * @param FileSystem $files @@ -360,6 +372,48 @@ public function get($columns = array()) } } + /** + * Parse the file in chunks + * @param [type] $size [description] + * @param [type] $callback [description] + * @return [type] [description] + */ + public function chunk($size = 10, $callback = null) + { + // Check if the chunk filter has been enabled + if(!in_array('chunk', $this->filters['enabled'])) + throw new \Exception("The chunk filter is not enabled, do so with ->filter('chunk')"); + + // Get total rows + $totalRows = $this->getTotalRowsOfFile(); + + // Only read + $this->reader->setReadDataOnly(true); + + // Start the chunking + for ($startRow = 1; $startRow <= $totalRows; $startRow += $size) + { + // Set the rows for the chunking + $this->filter->setRows($startRow, $size); + + // Load file with chunk filter enabled + $this->excel = $this->reader->load($this->file); + + // Set start index + $startIndex = ($startRow == 1) ? $startRow : $startRow - 1; + + // Slice the results + $results = $this->get()->slice($startIndex, $size); + + // Do a callback + if(is_callable($callback)) + call_user_func($callback, $results); + + $this->_reset(); + unset($this->excel, $results); + } + } + /** * Each * @param callback $callback @@ -425,6 +479,7 @@ protected function _init($file, $encoding = false) ->setTitle() ->_setFormat() ->_setReader() + ->_enableFilters() ->_setInputEncoding($encoding); } @@ -439,6 +494,42 @@ public function injectExcel($excel) $this->_reset(); } + /** + * Set filters + * @param array $filters + */ + public function setFilters($filters = array()) + { + $this->filters = $filters; + } + + /** + * Enable filters + * @return + */ + protected function _enableFilters() + { + // Loop through the registered filters + foreach($this->filters['registered'] as $key => $class) + { + // Set the filter inside the reader when enabled and the class exists + if(in_array($key, $this->filters['enabled']) && class_exists($class)) + { + // init new filter (and overrule the current) + $this->filter = new $class; + + // Set default rows + if(method_exists($this->filter, 'setRows')) + $this->filter->setRows(0, 1); + + // Set the read filter + $this->reader->setReadFilter($this->filter); + } + } + + return $this; + } + /** * Set the file * @param string $file @@ -668,6 +759,16 @@ public function getLimit() return $this->limit; } + /** + * Get total rows of file + * @return integer + */ + public function getTotalRowsOfFile() + { + $spreadsheetInfo = $this->reader->listWorksheetInfo($this->file); + return $spreadsheetInfo[0]['totalRows']; + } + /** * Set the write format * @return LaraveExcelReader @@ -759,6 +860,7 @@ protected function _setReaderDefaults() protected function _reset() { $this->excel->disconnectWorksheets(); + unset($this->parsed); } /** From ba54e252d69a22b73616afab8ca8419d7b50493b Mon Sep 17 00:00:00 2001 From: YAAK Date: Mon, 8 Sep 2014 12:17:02 -0400 Subject: [PATCH 0204/1332] Fixed a variable name in code documentation Changed $firstRowAsIndex to $encoding in '_init' and 'load' functions --- src/Maatwebsite/Excel/Readers/LaravelExcelReader.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index a2a29f92e..c1bd263b2 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -185,7 +185,7 @@ public function __construct(Filesystem $filesystem, FormatIdentifier $identifier /** * Load a file * @param string $file - * @param boolean $firstRowAsIndex + * @param string|boolean $encoding * @return LaravelExcelReader */ public function load($file, $encoding = false) @@ -468,7 +468,7 @@ public function dd($columns = array()) /** * Init the loading * @param string $file - * @param string|boolean $firstRowAsIndex + * @param string|boolean $encoding * @return void */ protected function _init($file, $encoding = false) @@ -898,4 +898,4 @@ public function __call($method, $params) } -} \ No newline at end of file +} From 3107cc1078cb38d95a432045bff6839df844cf27 Mon Sep 17 00:00:00 2001 From: Gabriel Machado Date: Wed, 10 Sep 2014 08:57:59 -0300 Subject: [PATCH 0205/1332] Backslash escape fix Backslash is a escape character in JSON. http://stackoverflow.com/a/19176131/2099835 This also make my IDE stop complain about syntax errors. --- provides.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/provides.json b/provides.json index d7f2a9d2c..fd6d5bbb0 100644 --- a/provides.json +++ b/provides.json @@ -1,11 +1,11 @@ { "providers": [ - "Maatwebsite\Excel\ExcelServiceProvider" + "Maatwebsite\\Excel\\ExcelServiceProvider" ], "aliases": [ { "alias": "Excel", - "facade": "Maatwebsite\Excel\Facades\Excel" + "facade": "Maatwebsite\\Excel\\Facades\\Excel" } ] -} \ No newline at end of file +} From 495a37f52f720b90b873f70d971d2684951cd55e Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 17:25:17 +0200 Subject: [PATCH 0206/1332] Define extra dependencies, fixes issue #200 --- composer.json | 21 +++++++++++-------- src/Maatwebsite/Excel/Classes/Cache.php | 2 +- .../Excel/Classes/LaravelExcelWorksheet.php | 2 +- src/Maatwebsite/Excel/Classes/PHPExcel.php | 2 +- .../Excel/ExcelServiceProvider.php | 2 +- src/Maatwebsite/Excel/Parsers/CssParser.php | 2 +- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 +- src/Maatwebsite/Excel/Parsers/ViewParser.php | 2 +- .../Excel/Readers/ConfigReader.php | 2 +- src/Maatwebsite/Excel/Readers/HtmlReader.php | 8 +++---- .../Excel/Readers/LaravelExcelReader.php | 4 ++-- .../Excel/Writers/LaravelExcelWriter.php | 4 ++-- 12 files changed, 28 insertions(+), 25 deletions(-) diff --git a/composer.json b/composer.json index 669b7ff51..a8eb92728 100644 --- a/composer.json +++ b/composer.json @@ -11,12 +11,21 @@ ], "require": { "php": ">=5.3.0", - "phpoffice/phpexcel": "~1.8.0" + "phpoffice/phpexcel": "~1.8.0", + "phpseclib/phpseclib": ">=0.3.7", + "illuminate/cache": "~4.0", + "illuminate/config": "~4.0", + "illuminate/filesystem": "~4.0", + "illuminate/http": "~4.0", + "illuminate/support": "~4.0", + "illuminate/routing": "~4.0", + "illuminate/view": "~4.0", + "nesbot/carbon": "~1.0" }, "require-dev": { "phpunit/phpunit": "~4.0", "mockery/mockery": "~0.9", - "orchestra/testbench": "~2.2.0@dev" + "orchestra/testbench": "~2.2.0" }, "autoload": { "classmap": [ @@ -26,11 +35,5 @@ "psr-0": { "Maatwebsite\\Excel\\": "src/" } - }, - "repositories": [ - { - "type": "vcs", - "url": "git://github.com/orchestral/phpseclib.git" - } - ] + } } diff --git a/src/Maatwebsite/Excel/Classes/Cache.php b/src/Maatwebsite/Excel/Classes/Cache.php index 784d3347f..260a49742 100644 --- a/src/Maatwebsite/Excel/Classes/Cache.php +++ b/src/Maatwebsite/Excel/Classes/Cache.php @@ -1,7 +1,7 @@ Date: Wed, 10 Sep 2014 19:04:24 +0200 Subject: [PATCH 0207/1332] Better html rowspan handling, fixes issue #169 --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 441 ++++++++++--------- 1 file changed, 242 insertions(+), 199 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index b98844b0f..7c195cf76 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -5,6 +5,7 @@ use DOMText; use DOMElement; use domDocument; +use PHPExcel_Cell; use PHPExcel_Settings; use PHPExcel_Reader_HTML; use PHPExcel_Style_Color; @@ -29,8 +30,7 @@ * @author Maatwebsite * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class Html extends PHPExcel_Reader_HTML -{ +class Html extends PHPExcel_Reader_HTML { /** * Input encoding @@ -42,13 +42,13 @@ class Html extends PHPExcel_Reader_HTML * Sheet index to read * @var int */ - private $_sheetIndex = 0; + private $_sheetIndex = 0; /** * HTML tags formatting settings * @var array */ - private $_formats = array(); + private $_formats = []; /** * The current colspan @@ -56,7 +56,7 @@ class Html extends PHPExcel_Reader_HTML */ protected $spanWidth = 1; - /** + /** * The current rowspan * @var integer */ @@ -65,8 +65,8 @@ class Html extends PHPExcel_Reader_HTML /** * Loads PHPExcel from file * - * @param string $pFilename - * @param boolean $isString + * @param string $pFilename + * @param boolean $isString * @param PHPExcel|LaravelExcelWorksheet|null $obj * @return LaravelExcelWorksheet * @throws PHPExcel_Reader_Exception @@ -76,18 +76,19 @@ public function load($pFilename, $isString = false, $obj = false) // Set the default style formats $this->setStyleFormats(); - if($obj instanceof PHPExcel) + if ($obj instanceof PHPExcel) { // Load into this instance return $this->loadIntoExisting($pFilename, $obj, $isString); } - elseif($obj instanceof LaravelExcelWorksheet) + elseif ($obj instanceof LaravelExcelWorksheet) { // Load into this instance return $this->loadIntoExistingSheet($pFilename, $obj, $isString); } $objPHPExcel = $obj ? $obj : new PHPExcel(); + return $this->loadIntoExisting($pFilename, $objPHPExcel, $isString); } @@ -97,39 +98,39 @@ public function load($pFilename, $isString = false, $obj = false) */ protected function setStyleFormats() { - $this->_formats = Config::get('excel::views.styles', array()); + $this->_formats = Config::get('excel::views.styles', []); } /** * Loads HTML from file into sheet instance * - * @param string $pFilename - * @param LaravelExcelWorksheet $sheet - * @param boolean $isString + * @param string $pFilename + * @param LaravelExcelWorksheet $sheet + * @param boolean $isString * @return LaravelExcelWorksheet * @throws PHPExcel_Reader_Exception */ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, $isString = false) { - $isHtmlFile = FALSE; + $isHtmlFile = false; // Check if it's a string or file - if(!$isString) + if (!$isString) { // Double check if it's a file - if(is_file($pFilename)) + if (is_file($pFilename)) { - $isHtmlFile = TRUE; - $this->_openFile($pFilename); + $isHtmlFile = true; + $this->_openFile($pFilename); - if (!$this->_isValidFormat()) - { - fclose ($this->_fileHandle); - throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid HTML file."); - } + if (!$this->_isValidFormat()) + { + fclose($this->_fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid HTML file."); + } - fclose ($this->_fileHandle); + fclose($this->_fileHandle); } } @@ -137,7 +138,7 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, $dom = new domDocument; // Check if we need to load the file or the HTML - if($isHtmlFile) + if ($isHtmlFile) { // Load HTML from file $loaded = @$dom->loadHTMLFile($pFilename, PHPExcel_Settings::getLibXmlLoaderOptions()); @@ -148,9 +149,9 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, $loaded = @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8')); } - if ($loaded === FALSE) + if ($loaded === false) { - throw new PHPExcel_Reader_Exception('Failed to load ',$pFilename,' as a DOM Document'); + throw new PHPExcel_Reader_Exception('Failed to load ', $pFilename, ' as a DOM Document'); } // Parse css @@ -162,9 +163,9 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, $row = 0; $column = 'A'; $content = ''; - $this->_processDomElement($dom,$sheet,$row,$column,$content); + $this->_processDomElement($dom, $sheet, $row, $column, $content); - if(!$sheet->hasFixedSizeColumns()) + if (!$sheet->hasFixedSizeColumns()) $this->autosizeColumn($sheet); return $sheet; @@ -177,9 +178,9 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, */ public function autosizeColumn($sheet) { - if($columns = $sheet->getAutosize()) + if ($columns = $sheet->getAutosize()) { - if(is_array($columns)) + if (is_array($columns)) { $sheet->setAutoSize($columns); } @@ -187,7 +188,8 @@ public function autosizeColumn($sheet) { $toCol = $sheet->getHighestColumn(); $toCol++; - for ($i = 'A'; $i !== $toCol; $i++) { + for ($i = 'A'; $i !== $toCol; $i++) + { $sheet->getColumnDimension($i)->setAutoSize(true); } @@ -200,43 +202,45 @@ public function autosizeColumn($sheet) /** * Process the dom element - * @param DOMNode $element - * @param LaravelExcelWorksheet $sheet - * @param string $row - * @param integer $column - * @param string $cellContent + * @param DOMNode $element + * @param LaravelExcelWorksheet $sheet + * @param string $row + * @param integer $column + * @param string $cellContent * @return void */ - private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, &$cellContent){ + private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, &$cellContent) + { - foreach($element->childNodes as $child){ + foreach ($element->childNodes as $child) + { // If is text if ($child instanceof DOMText) { // get the dom text - $domText = preg_replace('/\s+/u',' ',trim($child->nodeValue)); + $domText = preg_replace('/\s+/u', ' ', trim($child->nodeValue)); // simply append the text if the cell content is a plain text string - if (is_string($cellContent)) { + if (is_string($cellContent)) + { $cellContent .= $domText; } - } // If is a dom element - elseif($child instanceof DOMElement) + elseif ($child instanceof DOMElement) { - $attributeArray = array(); + $attributeArray = []; // Loop through the child's attributes - foreach($child->attributes as $attribute) + foreach ($child->attributes as $attribute) { // Add the attribute to the array $attributeArray[$attribute->name] = $attribute->value; // Attribute names - switch($attribute->name) + switch ($attribute->name) { // Inline css styles @@ -286,17 +290,19 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & } // nodeName - switch($child->nodeName) + switch ($child->nodeName) { // Meta tags case 'meta' : // Loop through the attributes - foreach($attributeArray as $attributeName => $attributeValue) { + foreach ($attributeArray as $attributeName => $attributeValue) + { // Switch the names - switch($attributeName) { + switch ($attributeName) + { // Set input encoding case 'charset': $_inputEncoding = $attributeValue; @@ -305,13 +311,13 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & } // Continue processing dom element - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); break; // Set sheet title case 'title' : - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); $sheet->setTitle($cellContent); $cellContent = ''; break; @@ -330,7 +336,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & $cellContent .= ' '; // Continue processing - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); // Add space after empty cells if ($cellContent > '') @@ -339,8 +345,8 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Set the styling if (isset($this->_formats[$child->nodeName])) { - $sheet->getStyle($column.$row) - ->applyFromArray($this->_formats[$child->nodeName]); + $sheet->getStyle($column . $row) + ->applyFromArray($this->_formats[$child->nodeName]); } break; @@ -349,7 +355,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & case 'hr' : // Flush the cell - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); // count ++$row; @@ -357,13 +363,13 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Set the styling if (isset($this->_formats[$child->nodeName])) { - $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + $sheet->getStyle($column . $row)->applyFromArray($this->_formats[$child->nodeName]); } // If not, enter cell content else { $cellContent = '----------'; - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); } ++$row; @@ -380,7 +386,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Otherwise flush our existing content and move the row cursor on else { - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); ++$row; } @@ -389,21 +395,21 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Hyperlinks case 'a' : - foreach($attributeArray as $attributeName => $attributeValue) + foreach ($attributeArray as $attributeName => $attributeValue) { - switch($attributeName) + switch ($attributeName) { case 'href': // Set the url - $sheet->getCell($column.$row) - ->getHyperlink() - ->setUrl($attributeValue); + $sheet->getCell($column . $row) + ->getHyperlink() + ->setUrl($attributeValue); // Set styling if (isset($this->_formats[$child->nodeName])) { - $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + $sheet->getStyle($column . $row)->applyFromArray($this->_formats[$child->nodeName]); } break; @@ -412,7 +418,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Add empty space $cellContent .= ' '; - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); break; @@ -430,29 +436,29 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & if ($this->_tableLevel > 0) { $cellContent .= "\n"; - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); // Set style if (isset($this->_formats[$child->nodeName])) { - $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + $sheet->getStyle($column . $row)->applyFromArray($this->_formats[$child->nodeName]); } } else { if ($cellContent > '') { - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); $row += 2; } - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); // Set style if (isset($this->_formats[$child->nodeName])) { - $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + $sheet->getStyle($column . $row)->applyFromArray($this->_formats[$child->nodeName]); } $row += 2; @@ -467,19 +473,19 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & { // If we're inside a table, replace with a \n $cellContent .= "\n"; - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); } else { if ($cellContent > '') { - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); } ++$row; - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); $column = 'A'; } break; @@ -488,7 +494,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & case 'table' : // Flush the cells - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); // Set the start column $column = $this->_setTableStartColumn($column); @@ -496,7 +502,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & if ($this->_tableLevel > 1) --$row; - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); // Release the table start column $column = $this->_releaseTableStartColumn(); @@ -504,7 +510,8 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & if ($this->_tableLevel > 1) { ++$column; - } else + } + else { ++$row; } @@ -514,7 +521,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Heading and body case 'thead' : case 'tbody' : - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); break; case 'img': @@ -531,15 +538,11 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & $cellContent = ''; // Continue processing - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); - // If we have a rowspan, count the right amount of rows, else just 1 - for($i = 0; $i < $this->spanHeight; $i++) - { - ++$row; - } + ++$row; - // reset the span height after the process + // reset the span height $this->spanHeight = 1; break; @@ -551,7 +554,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & $this->_processHeadings($child, $sheet, $row, $column, $cellContent); // If we have a colspan, count the right amount of columns, else just 1 - for($i = 0; $i < $this->spanWidth; $i++) + for ($w = 0; $w < $this->spanWidth; $w++) { ++$column; } @@ -564,11 +567,11 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Table cell case 'td' : - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); // If we have a colspan, count the right amount of columns, else just 1 - for($i = 0; $i < $this->spanWidth; $i++) + for ($w = 0; $w < $this->spanWidth; $w++) { ++$column; } @@ -584,12 +587,12 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & $column = 'A'; $content = ''; $this->_tableLevel = 0; - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); break; // Default default: - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); } } } @@ -630,19 +633,22 @@ private function _getTableStartColumn() private function _releaseTableStartColumn() { --$this->_tableLevel; + return array_pop($this->_nestedColumn); } /** * Flush the cells * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $cellContent + * @param string $column + * @param integer $row + * @param string $cellContent * @return void */ - private function _flushCell($sheet,$column,$row,&$cellContent) + private function _flushCell($sheet, &$column, $row, &$cellContent) { + // Process merged cells + list($column, $cellContent) = $this->processMergedCells($sheet, $column, $row, $cellContent); if (is_string($cellContent)) { @@ -652,14 +658,13 @@ private function _flushCell($sheet,$column,$row,&$cellContent) // Only actually write it if there's content in the string // Write to worksheet to be done here... // ... we return the cell so we can mess about with styles more easily - $cell = $sheet->setCellValue($column.$row,$cellContent,true); + + $cell = $sheet->setCellValue($column . $row, $cellContent, true); $this->_dataArray[$row][$column] = $cellContent; } } else { - // We have a Rich Text run - // TODO $this->_dataArray[$row][$column] = 'RICH TEXT: ' . $cellContent; } $cellContent = (string) ''; @@ -667,20 +672,21 @@ private function _flushCell($sheet,$column,$row,&$cellContent) /** * Process table headings - * @param string $child + * @param string $child * @param LaravelExcelWorksheet $sheet - * @param string $row - * @param integer $column + * @param string $row + * @param integer $column * @return LaravelExcelWorksheet */ protected function _processHeadings($child, $sheet, $row, $column, $cellContent) { - $this->_processDomElement($child,$sheet,$row,$column,$cellContent); - $this->_flushCell($sheet,$column,$row,$cellContent); + $this->_processDomElement($child, $sheet, $row, $column, $cellContent); + $this->_flushCell($sheet, $column, $row, $cellContent); - if (isset($this->_formats[$child->nodeName])) { - $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + if (isset($this->_formats[$child->nodeName])) + { + $sheet->getStyle($column . $row)->applyFromArray($this->_formats[$child->nodeName]); } return $sheet; @@ -689,19 +695,19 @@ protected function _processHeadings($child, $sheet, $row, $column, $cellContent) /** * Style the element by class * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $class + * @param string $column + * @param integer $row + * @param string $class * @return void */ protected function styleByClass($sheet, $column, $row, $class) { // If the class has a whitespace // break into multiple classes - if(str_contains($class, ' ')) + if (str_contains($class, ' ')) { $classes = explode(' ', $class); - foreach($classes as $class) + foreach ($classes as $class) { return $this->styleByClass($sheet, $column, $row, $class); } @@ -711,7 +717,7 @@ protected function styleByClass($sheet, $column, $row, $class) $styles = $this->css->lookup('class', $class); // Loop through the styles - foreach($styles as $name => $value) + foreach ($styles as $name => $value) { $this->parseCssProperties($sheet, $column, $row, $name, $value); } @@ -720,16 +726,16 @@ protected function styleByClass($sheet, $column, $row, $class) /** * Style the element by class * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $class + * @param string $column + * @param integer $row + * @param string $class * @return void */ protected function styleById($sheet, $column, $row, $class) { $styles = $this->css->lookup('id', $class); - foreach($styles as $name => $value) + foreach ($styles as $name => $value) { $this->parseCssProperties($sheet, $column, $row, $name, $value); } @@ -738,18 +744,18 @@ protected function styleById($sheet, $column, $row, $class) /** * Insert a image inside the sheet * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $attributes + * @param string $column + * @param integer $row + * @param string $attributes * @return void */ protected function insertImageBySrc($sheet, $column, $row, $attributes) { // Get attributes - $src = $attributes->getAttribute('src'); - $width = (float) $attributes->getAttribute('width'); + $src = $attributes->getAttribute('src'); + $width = (float) $attributes->getAttribute('width'); $height = (float) $attributes->getAttribute('height'); - $alt = $attributes->getAttribute('alt'); + $alt = $attributes->getAttribute('alt'); // init drawing $drawing = new PHPExcel_Worksheet_Drawing(); @@ -762,10 +768,10 @@ protected function insertImageBySrc($sheet, $column, $row, $attributes) $drawing->setResizeProportional(); // Set height and width - if($width > 0) + if ($width > 0) $drawing->setWidth($width); - if($height > 0) + if ($height > 0) $drawing->setHeight($height); // Set cell width based on image @@ -776,9 +782,9 @@ protected function insertImageBySrc($sheet, $column, $row, $attributes) /** * Set column width * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param integer $width + * @param string $column + * @param integer $row + * @param integer $width * @return void */ protected function parseWidth($sheet, $column, $row, $width) @@ -789,9 +795,9 @@ protected function parseWidth($sheet, $column, $row, $width) /** * Set row height * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param integer $height + * @param string $column + * @param integer $row + * @param integer $height * @return void */ protected function parseHeight($sheet, $column, $row, $height) @@ -802,25 +808,25 @@ protected function parseHeight($sheet, $column, $row, $height) /** * Parse colspans * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param integer $spanWidth + * @param string $column + * @param integer $row + * @param integer $spanWidth * @return void */ protected function parseColSpan($sheet, $column, $row, $spanWidth) { - $startCell = $column.$row; + $startCell = $column . $row; $this->spanWidth = $spanWidth; // Find end column letter - for($i = 0; $i < ($spanWidth - 1); $i++) + for ($i = 0; $i < ($spanWidth - 1); $i++) { ++$column; } // Set endcell - $endCell = ($column).$row; + $endCell = ($column) . $row; // Set range $range = $startCell . ':' . $endCell; @@ -832,38 +838,42 @@ protected function parseColSpan($sheet, $column, $row, $spanWidth) /** * Parse colspans * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param integer $spanHeight + * @param string $column + * @param integer $row + * @param integer $spanHeight * @return void */ protected function parseRowSpan($sheet, $column, $row, $spanHeight) { - // Set the spanHeight - $this->spanHeight = $spanHeight; + // Set the span height + $this->spanHeight = --$spanHeight; - $startCell = $column.$row; - $endCell = $column.($row * $spanHeight); + // Set start cell + $startCell = $column . $row; + + // Set endcell = current row number + spanheight + $endCell = $column . ($row + $this->spanHeight); $range = $startCell . ':' . $endCell; + // Merge the cells $sheet->mergeCells($range); } /** * Parse the align * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $value + * @param string $column + * @param integer $row + * @param string $value * @return void */ protected function parseAlign($sheet, $column, $row, $value) { $horizontal = false; - $cells = $sheet->getStyle($column.$row); + $cells = $sheet->getStyle($column . $row); - switch($value) + switch ($value) { case 'center': $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_CENTER; @@ -882,27 +892,27 @@ protected function parseAlign($sheet, $column, $row, $value) break; } - if($horizontal) + if ($horizontal) $cells->getAlignment()->applyFromArray( - array('horizontal' => $horizontal) + ['horizontal' => $horizontal] ); } /** * Parse the valign * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $value + * @param string $column + * @param integer $row + * @param string $value * @return void */ protected function parseValign($sheet, $column, $row, $value) { $vertical = false; - $cells = $sheet->getStyle($column.$row); + $cells = $sheet->getStyle($column . $row); - switch($value) + switch ($value) { case 'top': $vertical = PHPExcel_Style_Alignment::VERTICAL_TOP; @@ -921,18 +931,18 @@ protected function parseValign($sheet, $column, $row, $value) break; } - if($vertical) + if ($vertical) $cells->getAlignment()->applyFromArray( - array('vertical' => $vertical) + ['vertical' => $vertical] ); } /** * Parse the inline styles * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $styleTag + * @param string $column + * @param integer $row + * @param string $styleTag * @return void */ protected function parseInlineStyles($sheet, $column, $row, $styleTag) @@ -946,14 +956,14 @@ protected function parseInlineStyles($sheet, $column, $row, $styleTag) /** * Parse the styles * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param array @styles + * @param string $column + * @param integer $row + * @param array @styles * @return void */ - protected function parseCssAttributes($sheet, $column, $row, $styles = array()) + protected function parseCssAttributes($sheet, $column, $row, $styles = []) { - foreach($styles as $tag) + foreach ($styles as $tag) { $style = explode(':', $tag); $name = trim(reset($style)); @@ -966,16 +976,16 @@ protected function parseCssAttributes($sheet, $column, $row, $styles = array()) /** * Parse CSS * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $name - * @param string $value + * @param string $column + * @param integer $row + * @param string $name + * @param string $value * @return void */ protected function parseCssProperties($sheet, $column, $row, $name, $value) { - $cells = $sheet->getStyle($column.$row); - switch($name) + $cells = $sheet->getStyle($column . $row); + switch ($name) { // Cell width case 'width': @@ -993,12 +1003,12 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) $value = $this->getColor($value); $cells->applyFromArray( - array( - 'fill' => array( - 'type' => PHPExcel_Style_Fill::FILL_SOLID, - 'color' => array ('rgb' => $value) - ) - ) + [ + 'fill' => [ + 'type' => PHPExcel_Style_Fill::FILL_SOLID, + 'color' => ['rgb' => $value] + ] + ] ); break; @@ -1006,7 +1016,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) case 'color': $value = $this->getColor($value); $cells->getFont()->getColor()->applyFromArray( - array('rgb' => $value) + ['rgb' => $value] ); break; @@ -1017,26 +1027,26 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) // FONT WEIGHT case 'font-weight': - if($value == 'bold' || $value >= 500) + if ($value == 'bold' || $value >= 500) $cells->getFont()->setBold(true); break; // FONT STYLE case 'font-style': - if($value == 'italic') + if ($value == 'italic') $cells->getFont()->setItalic(true); break; // FONT FACE case 'font-family': $cells->getFont()->applyFromArray( - array('name' => $value) + ['name' => $value] ); break; // TEXT DECORATION case 'text-decoration': - switch($value) + switch ($value) { case 'underline': $cells->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); @@ -1053,7 +1063,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) $horizontal = false; - switch($value) + switch ($value) { case 'center': $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_CENTER; @@ -1072,9 +1082,9 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) break; } - if($horizontal) + if ($horizontal) $cells->getAlignment()->applyFromArray( - array('horizontal' => $horizontal) + ['horizontal' => $horizontal] ); break; @@ -1084,7 +1094,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) $vertical = false; - switch($value) + switch ($value) { case 'top': $vertical = PHPExcel_Style_Alignment::VERTICAL_TOP; @@ -1101,12 +1111,11 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) case 'justify': $vertical = PHPExcel_Style_Alignment::VERTICAL_JUSTIFY; break; - } - if($vertical) + if ($vertical) $cells->getAlignment()->applyFromArray( - array('vertical' => $vertical) + ['vertical' => $vertical] ); break; @@ -1120,7 +1129,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) $borderStyle = $this->borderStyle($style); $cells->getBorders()->applyFromArray( - array( 'allborders' => array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color ) ) ) + ['allborders' => ['style' => $borderStyle, 'color' => ['rgb' => $color]]] ); break; @@ -1134,7 +1143,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) $borderStyle = $this->borderStyle($style); $cells->getBorders()->getTop()->applyFromArray( - array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) + ['style' => $borderStyle, 'color' => ['rgb' => $color]] ); break; @@ -1147,7 +1156,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) $borderStyle = $this->borderStyle($style); $cells->getBorders()->getBottom()->applyFromArray( - array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) + ['style' => $borderStyle, 'color' => ['rgb' => $color]] ); break; @@ -1160,7 +1169,7 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) $borderStyle = $this->borderStyle($style); $cells->getBorders()->getRight()->applyFromArray( - array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) + ['style' => $borderStyle, 'color' => ['rgb' => $color]] ); break; @@ -1173,10 +1182,9 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) $borderStyle = $this->borderStyle($style); $cells->getBorders()->getLeft()->applyFromArray( - array( 'style' => $borderStyle, 'color' => array( 'rgb' => $color )) + ['style' => $borderStyle, 'color' => ['rgb' => $color]] ); break; - } } @@ -1190,7 +1198,7 @@ public function getColor($color) $color = str_replace('#', '', $color); // If color is only 3 chars long, mirror it to 6 chars - if(strlen($color) == 3) + if (strlen($color) == 3) $color = $color . $color; return $color; @@ -1203,7 +1211,8 @@ public function getColor($color) */ public function borderStyle($style) { - switch($style) { + switch ($style) + { case 'solid'; return PHPExcel_Style_Border::BORDER_THIN; break; @@ -1230,4 +1239,38 @@ public function borderStyle($style) } } -} + /** + * @param $sheet + * @param $column + * @param $row + * @return array + */ + private function processMergedCells($sheet, &$column, $row, $cellContent) + { + // Find the cells + $cell = $sheet->getCell($column . $row); + + // Get the merged cells + foreach ($sheet->getMergeCells() as $mergedCells) + { + // If cells is in the merged cells range + if ($cell->isInRange($mergedCells)) + { + // Get columns + preg_match("/(.*):(.*?)/u", $mergedCells, $matches); + + // skip the first item in the merge + if ($matches[1] != $column . $row) + { + $newCol = PHPExcel_Cell::stringFromColumnIndex( + (PHPExcel_Cell::columnIndexFromString($column) + 1) - 1 + ); + $column = $newCol; + $this->_flushCell($sheet, $newCol, $row, $cellContent); + } + } + } + + return [$column, $cellContent]; + } +} \ No newline at end of file From 0534f5b5b2efee2e548a062a6c90afa539e01243 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 19:12:13 +0200 Subject: [PATCH 0208/1332] Drop use of ::make for CellCollection to support L4.3 --- .../Excel/Collections/CellCollection.php | 20 +++---------------- src/Maatwebsite/Excel/Parsers/CssParser.php | 2 +- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 2 +- 3 files changed, 5 insertions(+), 19 deletions(-) diff --git a/src/Maatwebsite/Excel/Collections/CellCollection.php b/src/Maatwebsite/Excel/Collections/CellCollection.php index aa0e3e48c..a350eb182 100644 --- a/src/Maatwebsite/Excel/Collections/CellCollection.php +++ b/src/Maatwebsite/Excel/Collections/CellCollection.php @@ -5,7 +5,6 @@ * LaravelExcel CellCollection * * @category Laravel Excel - * @version 1.0.0 * @package maatwebsite/excel * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) * @author Maatwebsite @@ -15,27 +14,14 @@ class CellCollection extends ExcelCollection { /** * Create a new collection. - * - * @param array $items - * @return void + * @param array $items + * @return \Maatwebsite\Excel\Collections\CellCollection */ - public function __construct(array $items = array()) + public function __construct(array $items = []) { $this->setItems($items); } - /** - * Create a new collection instance if the value isn't one already. - * - * @param mixed $items - * @return \Illuminate\Support\Collection - */ - public static function make($items) - { - if (is_null($items)) return new static; - return new static(is_array($items) ? $items : array($items)); - } - /** * Set the items * @param array $items diff --git a/src/Maatwebsite/Excel/Parsers/CssParser.php b/src/Maatwebsite/Excel/Parsers/CssParser.php index 3d2a7cb12..dbb2fd4ce 100644 --- a/src/Maatwebsite/Excel/Parsers/CssParser.php +++ b/src/Maatwebsite/Excel/Parsers/CssParser.php @@ -22,7 +22,7 @@ class CssParser { protected $results = array(); /** - * Preg match string + * Preg match stringmake * @var string */ protected $matcher = '/(.+?)\s?\{\s?(.+?)\s?\}/'; diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 7df9fa913..33f61e381 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -410,7 +410,7 @@ protected function parseCells() } // Return array with parsed cells - return CellCollection::make($parsedCells); + return new CellCollection($parsedCells); } /** From 60a4132f70bb1e26abdc6dc347fb5c9832ff4eeb Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 19:42:21 +0200 Subject: [PATCH 0209/1332] Workarround for long integers, fixes issue #183 --- .../Excel/Classes/LaravelExcelWorksheet.php | 397 +++++++++++------- .../Excel/Collections/ExcelCollection.php | 1 - 2 files changed, 237 insertions(+), 161 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index bd4d8e469..f3fd90efd 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -1,6 +1,8 @@ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class LaravelExcelWorksheet extends PHPExcel_Worksheet -{ +class LaravelExcelWorksheet extends PHPExcel_Worksheet { + /** * Parent * @var PHPExcel @@ -43,19 +45,19 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet * Data * @var array */ - public $data = array(); + public $data = []; /** * Merge data * @var array */ - public $mergeData = array(); + public $mergeData = []; /** * Allowed page setup * @var array */ - public $allowedPageSetup = array( + public $allowedPageSetup = [ 'orientation', 'paperSize', 'scale', @@ -68,17 +70,17 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet 'verticalCentered', 'printArea', 'firstPageNumber' - ); + ]; /** * Allowed page setup * @var array */ - public $allowedStyles = array( + public $allowedStyles = [ 'fontFamily', 'fontSize', 'fontBold' - ); + ]; /** * Check if the file was autosized @@ -95,8 +97,8 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet /** * Create a new worksheet * - * @param PHPExcel $pParent - * @param string $pTitle + * @param PHPExcel $pParent + * @param string $pTitle */ public function __construct(PHPExcel $pParent = null, $pTitle = 'Worksheet') { @@ -113,17 +115,17 @@ public function setDefaultPageSetup() // Get the page setup $pageSetup = $this->getPageSetup(); - foreach($this->allowedPageSetup as $setup) + foreach ($this->allowedPageSetup as $setup) { // set the setter list($setter, $set) = $this->_setSetter($setup); // get the value - $value = Config::get('excel::sheets.pageSetup.' . $setup, NULL); + $value = Config::get('excel::sheets.pageSetup.' . $setup, null); // Set the page setup value - if(!is_null($value)) - call_user_func_array(array($pageSetup, $setter), array($value)); + if (!is_null($value)) + call_user_func_array([$pageSetup, $setter], [$value]); } // Set default page margins @@ -136,9 +138,9 @@ public function setDefaultPageSetup() */ public function setPageMargin($margin = false) { - if(!is_array($margin)) + if (!is_array($margin)) { - $marginArray = array($margin, $margin, $margin, $margin); + $marginArray = [$margin, $margin, $margin, $margin]; } else { @@ -148,36 +150,37 @@ public function setPageMargin($margin = false) // Get margin $pageMargin = $this->getPageMargins(); - if(isset($marginArray[0])) + if (isset($marginArray[0])) $pageMargin->setTop($marginArray[0]); - if(isset($marginArray[1])) + if (isset($marginArray[1])) $pageMargin->setRight($marginArray[1]); - if(isset($marginArray[2])) + if (isset($marginArray[2])) $pageMargin->setBottom($marginArray[2]); - if(isset($marginArray[3])) + if (isset($marginArray[3])) $pageMargin->setLeft($marginArray[3]); } /** * Manipulate a single row - * @param integer|callback|array $rowNumber - * @param array|callback $callback + * @param integer|callback|array $rowNumber + * @param array|callback $callback * @return LaravelExcelWorksheet */ public function row($rowNumber, $callback = null) { // If a callback is given, handle it with the cell writer - if($callback instanceof Closure) + if ($callback instanceof Closure) { $range = $this->rowToRange($rowNumber); + return $this->cells($range, $callback); } // Else if the 2nd param was set, we will use it as a cell value - if(is_array($callback)) + if (is_array($callback)) { // Interpret the callback as cell values $values = $callback; @@ -185,7 +188,7 @@ public function row($rowNumber, $callback = null) // Set start column $column = 'A'; - foreach($values as $rowValue) + foreach ($values as $rowValue) { // Set cell coordinate $cell = $column . $rowNumber; @@ -194,7 +197,6 @@ public function row($rowNumber, $callback = null) $this->setCellValue($cell, $rowValue); $column++; } - } return $this; @@ -202,16 +204,16 @@ public function row($rowNumber, $callback = null) /** * Add multiple rows - * @param array $rows + * @param array $rows * @return LaravelExcelWorksheet */ - public function rows($rows = array()) + public function rows($rows = []) { // Get the start row $startRow = $this->getStartRow(); // Add rows - foreach($rows as $row) + foreach ($rows as $row) { $this->row($startRow, $row); $startRow++; @@ -222,14 +224,14 @@ public function rows($rows = array()) /** * Prepend a row - * @param integer $rowNumber - * @param array|callback $callback + * @param integer $rowNumber + * @param array|callback $callback * @return LaravelExcelWorksheet */ public function prependRow($rowNumber = 1, $callback = null) { // If only one param was given, prepend it before the first row - if(is_null($callback)) + if (is_null($callback)) { $callback = $rowNumber; $rowNumber = 1; @@ -245,13 +247,13 @@ public function prependRow($rowNumber = 1, $callback = null) /** * Append a row * @param integer|callback $rowNumber - * @param array|callback $callback + * @param array|callback $callback * @return LaravelExcelWorksheet */ public function appendRow($rowNumber = 1, $callback = null) { // If only one param was given, add it as very last - if(is_null($callback)) + if (is_null($callback)) { $callback = $rowNumber; $rowNumber = $this->getStartRow(); @@ -263,18 +265,18 @@ public function appendRow($rowNumber = 1, $callback = null) /** * Manipulate a single cell - * @param array|string $cell - * @param callback $callback + * @param array|string $cell + * @param callback $callback * @return LaravelExcelWorksheet */ public function cell($cell, $callback = false) { // If a callback is given, handle it with the cell writer - if($callback instanceof Closure) + if ($callback instanceof Closure) return $this->cells($cell, $callback); // Else if the 2nd param was set, we will use it as a cell value - if($callback) + if ($callback) $this->sheet->setCellValue($cell, $callback); return $this; @@ -282,7 +284,7 @@ public function cell($cell, $callback = false) /** * Manipulate a cell or a range of cells - * @param array $cells + * @param array $cells * @param callback $callback * @return LaravelExcelWorksheet */ @@ -292,7 +294,7 @@ public function cells($cells, $callback = false) $cells = new CellWriter($cells, $this); // Do the callback - if($callback instanceof Closure) + if ($callback instanceof Closure) call_user_func($callback, $cells); return $this; @@ -300,27 +302,27 @@ public function cells($cells, $callback = false) /** * Load a View and convert to HTML - * @param string $view - * @param array $data - * @param array $mergeData - * @return LaravelExcelWorksheet + * @param string $view + * @param array $data + * @param array $mergeData + * @return LaravelExcelWorksheet */ public function setView() { - return call_user_func_array(array($this, 'loadView'), func_get_args()); + return call_user_func_array([$this, 'loadView'], func_get_args()); } /** * Load a View and convert to HTML - * @param string $view - * @param array $data - * @param array $mergeData - * @return LaravelExcelWorksheet + * @param string $view + * @param array $data + * @param array $mergeData + * @return LaravelExcelWorksheet */ - public function loadView($view, $data = array(), $mergeData = array()) + public function loadView($view, $data = [], $mergeData = []) { // Init the parser - if(!$this->parser) + if (!$this->parser) $this->setParser(); $this->parser->setView($view); @@ -337,6 +339,7 @@ public function loadView($view, $data = array(), $mergeData = array()) public function unsetView() { $this->parser = null; + return $this; } @@ -359,14 +362,14 @@ public function getView() return $this->parser; } - /** + /** * Return parsed sheet * @return LaravelExcelWorksheet */ public function parsed() { // If parser is set, use it - if($this->parser) + if ($this->parser) return $this->parser->parse($this); // Else return the entire sheet @@ -375,9 +378,9 @@ public function parsed() /** * Set data for the current sheet - * @param string $keys - * @param string $value - * @param boolean $headingGeneration + * @param string $keys + * @param string $value + * @param boolean $headingGeneration * @return LaravelExcelWorksheet */ public function with($key, $value = false, $headingGeneration = true) @@ -387,16 +390,17 @@ public function with($key, $value = false, $headingGeneration = true) // Add the vars $this->_addVars($key, $value); + return $this; } /** * From array * @param Collection|array $source - * @param boolean $headingGeneration + * @param boolean $headingGeneration * @return LaravelExcelWorksheet */ - public function fromModel($source = NULL, $nullValue = null, $startCell = false, $strictNullComparison = false, $headingGeneration = true) + public function fromModel($source = null, $nullValue = null, $startCell = false, $strictNullComparison = false, $headingGeneration = true) { return $this->fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration); } @@ -404,9 +408,9 @@ public function fromModel($source = NULL, $nullValue = null, $startCell = false, /** * Fill worksheet from values in array * - * @param array $source Source array - * @param mixed $nullValue Value in source array that stands for blank cell - * @param string $startCell Insert array starting from this cell address as the top left coordinate + * @param array $source Source array + * @param mixed $nullValue Value in source array that stands for blank cell + * @param string $startCell Insert array starting from this cell address as the top left coordinate * @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array * @throws PHPExcel_Exception * @return LaravelExcelWorksheet @@ -414,8 +418,8 @@ public function fromModel($source = NULL, $nullValue = null, $startCell = false, public function fromArray($source = null, $nullValue = null, $startCell = false, $strictNullComparison = false, $headingGeneration = true) { // Set defaults - $nullValue = !is_null($nullValue) ? $nullValue : $this->getDefaultNullValue(); - $startCell = $startCell ? $startCell : $this->getDefaultStartCell(); + $nullValue = !is_null($nullValue) ? $nullValue : $this->getDefaultNullValue(); + $startCell = $startCell ? $startCell : $this->getDefaultStartCell(); $strictNullComparison = $strictNullComparison ? $strictNullComparison : $this->getDefaultStrictNullComparison(); // Set the heading generation setting @@ -424,29 +428,73 @@ public function fromArray($source = null, $nullValue = null, $startCell = false, // Add the vars $this->_addVars($source); - return parent::fromArray($this->data, $nullValue, $startCell, $strictNullComparison); + if (is_array($source)) + { + // Convert a 1-D array to 2-D (for ease of looping) + if (!is_array(end($source))) + { + $source = [$source]; + } + + // start coordinate + list ($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($startCell); + + // Loop through $source + foreach ($source as $rowData) + { + $currentColumn = $startColumn; + foreach ($rowData as $cellValue) + { + if ($strictNullComparison) + { + if ($cellValue !== $nullValue) + { + // Set cell value + $this->setValueOfCell($cellValue, $currentColumn, $startRow); + } + } + else + { + if ($cellValue != $nullValue) + { + // Set cell value + $this->setValueOfCell($cellValue, $currentColumn, $startRow); + } + } + ++$currentColumn; + } + ++$startRow; + } + } + else + { + throw new PHPExcel_Exception("Parameter \$source should be an array."); + } + + return $this; } /** * Add vars to the data array - * @param string $key + * @param string $key * @param string $value * @return void */ protected function _addVars($key, $value = false) { // Add array of data - if(is_array($key) || $key instanceof Collection) + if (is_array($key) || $key instanceof Collection) { // Set the data $this->data = $this->addData($key); // Create excel from array without a view - if(!$this->parser) + if (!$this->parser) { - $nullValue = $this->getDefaultNullValue(); - $startCell = $this->getDefaultStartCell(); + $nullValue = $this->getDefaultNullValue(); + $startCell = $this->getDefaultStartCell(); $strictNullComparison = $this->getDefaultStrictNullComparison(); + return parent::fromArray($this->data, $nullValue, $startCell, $strictNullComparison); } } @@ -458,7 +506,7 @@ protected function _addVars($key, $value = false) } // Set data to parser - if($this->parser) + if ($this->parser) $this->parser->setData($this->data); } @@ -470,7 +518,7 @@ protected function _addVars($key, $value = false) protected function addData($array) { // If a parser was set - if($this->parser) + if ($this->parser) { // Don't change anything $data = $array; @@ -478,24 +526,24 @@ protected function addData($array) else { // Transform model/collection to array - if($array instanceof Collection) + if ($array instanceof Collection) $array = $array->toArray(); // Get the firstRow $firstRow = reset($array); // Check if the array has array values - if(count($firstRow) != count($firstRow, 1)) + if (count($firstRow) != count($firstRow, 1)) { // Loop through the data to remove arrays - $data = array(); + $data = []; $r = 0; - foreach($array as $row) + foreach ($array as $row) { - $data[$r] = array(); - foreach($row as $key => $cell) + $data[$r] = []; + foreach ($row as $key => $cell) { - if(!is_array($cell)) + if (!is_array($cell)) { $data[$r][$key] = $cell; } @@ -509,12 +557,12 @@ protected function addData($array) } // Check if we should auto add the first row based on the indices - if($this->generateHeadingByIndices()) + if ($this->generateHeadingByIndices()) { // Get the first row $firstRow = reset($data); - if(is_array($firstRow)) + if (is_array($firstRow)) { // Get the array keys $tableHeading = array_keys($firstRow); @@ -523,11 +571,10 @@ protected function addData($array) array_unshift($data, $tableHeading); } } - } // Add results - if(!empty($data)) + if (!empty($data)) $this->data = !empty($this->data) ? array_merge($this->data, $data) : $data; // return data @@ -542,6 +589,7 @@ protected function addData($array) public function setAutoHeadingGeneration($boolean) { $this->autoGenerateHeading = $boolean; + return $this; } @@ -553,6 +601,7 @@ public function setAutoHeadingGeneration($boolean) public function disableHeadingGeneration($boolean = false) { $this->setAutoHeadingGeneration($boolean); + return $this; } @@ -562,7 +611,7 @@ public function disableHeadingGeneration($boolean = false) */ protected function generateHeadingByIndices() { - if(!$this->autoGenerateHeading) + if (!$this->autoGenerateHeading) return false; return Config::get('excel::export.generate_heading_by_indices', false); @@ -570,7 +619,7 @@ protected function generateHeadingByIndices() /** * Set attributes - * @param string $key + * @param string $key * @param array|string $params * @return void|PHPExcel_Worksheet_PageSetup */ @@ -580,40 +629,40 @@ public function _setAttributes($setter, $params) list($setter, $key) = $this->_setSetter($setter); // If is page setup - if(in_array($key, $this->allowedPageSetup)) + if (in_array($key, $this->allowedPageSetup)) { // Set params - $params = is_array($params) ? $params : array($params); + $params = is_array($params) ? $params : [$params]; // Call the setter - return call_user_func_array(array($this->getPageSetup(), $setter), $params); + return call_user_func_array([$this->getPageSetup(), $setter], $params); } // If is a style - elseif(in_array($key, $this->allowedStyles) ) + elseif (in_array($key, $this->allowedStyles)) { $this->setDefaultStyles($setter, $key, $params); } - throw new LaravelExcelException('[ERROR] Laravel Worksheet method ['. $setter .'] does not exist.'); + throw new LaravelExcelException('[ERROR] Laravel Worksheet method [' . $setter . '] does not exist.'); } /** * Set default styles - * @param string $setter - * @param string $key + * @param string $setter + * @param string $key * @param array|string $params * @return PHPExcel_Style */ protected function setDefaultStyles($setter, $key, $params) { $caller = $this->getDefaultStyle(); - $params = is_array($params) ? $params : array($params); + $params = is_array($params) ? $params : [$params]; - if(str_contains($key, 'font')) + if (str_contains($key, 'font')) return $this->setFontStyle($caller, $setter, $key, $params); - return call_user_func_array(array($caller, $setter), $params); + return call_user_func_array([$caller, $setter], $params); } /** @@ -624,6 +673,7 @@ protected function setDefaultStyles($setter, $key, $params) public function setStyle($styles) { $this->getDefaultStyle()->applyFromArray($styles); + return $this; } @@ -634,18 +684,19 @@ public function setStyle($styles) */ public function setFont($fonts) { - foreach($fonts as $key => $value) + foreach ($fonts as $key => $value) { $this->setFontStyle($this->getDefaultStyle(), $key, $key, $value); } + return $this; } /** * Set default font styles - * @param string $caller - * @param string $setter - * @param string $key + * @param string $caller + * @param string $setter + * @param string $key * @param array|string $params * @return PHPExcel_Style */ @@ -653,7 +704,7 @@ protected function setFontStyle($caller, $setter, $key, $params) { // Set caller to font $caller = $caller->getFont(); - $params = is_array($params) ? $params : array($params); + $params = is_array($params) ? $params : [$params]; // Clean the setter name $key = lcfirst(str_replace('font', '', $key)); @@ -661,14 +712,14 @@ protected function setFontStyle($caller, $setter, $key, $params) // Get setter method list($setter, $key) = $this->_setSetter($key); - switch($key) + switch ($key) { case 'family': $setter = 'setName'; break; } - return call_user_func_array(array($caller, $setter), $params); + return call_user_func_array([$caller, $setter], $params); } /** @@ -678,7 +729,7 @@ protected function setFontStyle($caller, $setter, $key, $params) */ protected function _setSetter($setter) { - if(starts_with($setter, 'set')) + if (starts_with($setter, 'set')) { $key = lcfirst(str_replace('set', '', $setter)); } @@ -689,10 +740,10 @@ protected function _setSetter($setter) } // Return the setter method and the key - return array($setter, $key); + return [$setter, $key]; } - /** + /** * Set the parent (excel object) * @param PHPExcel $parent */ @@ -712,17 +763,17 @@ public function getParent() /** * Set the column width - * @param string|array $column - * @param boolean $value + * @param string|array $column + * @param boolean $value * @return LaravelExcelWorksheet */ public function setWidth($column, $value = false) { // if is array of columns - if(is_array($column)) + if (is_array($column)) { // Set width for each column - foreach($column as $subColumn => $subValue) + foreach ($column as $subColumn => $subValue) { $this->setWidth($subColumn, $subValue); } @@ -731,8 +782,8 @@ public function setWidth($column, $value = false) { // Disable the autosize and set column width $this->getColumnDimension($column) - ->setAutoSize(false) - ->setWidth($value); + ->setAutoSize(false) + ->setWidth($value); // Set autosized to true $this->hasFixedSizeColumns = true; @@ -743,17 +794,17 @@ public function setWidth($column, $value = false) /** * Set the row height - * @param integer|array $row - * @param boolean $value + * @param integer|array $row + * @param boolean $value * @return LaravelExcelWorksheet */ public function setHeight($row, $value = false) { // if is array of columns - if(is_array($row)) + if (is_array($row)) { // Set width for each column - foreach($row as $subRow => $subValue) + foreach ($row as $subRow => $subValue) { $this->setHeight($subRow, $subValue); } @@ -769,18 +820,18 @@ public function setHeight($row, $value = false) /** * Set cell size - * @param array|string $cell - * @param integer $width - * @param integer $height + * @param array|string $cell + * @param integer $width + * @param integer $height * @return LaravelExcelWorksheet */ public function setSize($cell, $width = false, $height = false) { // if is array of columns - if(is_array($cell)) + if (is_array($cell)) { // Set width for each column - foreach($cell as $subCell => $sizes) + foreach ($cell as $subCell => $sizes) { $this->setSize($subCell, reset($sizes), end($sizes)); } @@ -788,14 +839,13 @@ public function setSize($cell, $width = false, $height = false) else { // Split the cell to column and row - list($column, $row) = preg_split('/(?<=[a-z])(?=[0-9]+)/i',$cell); + list($column, $row) = preg_split('/(?<=[a-z])(?=[0-9]+)/i', $cell); - if($column) + if ($column) $this->setWidth($column, $width); - if($row) + if ($row) $this->setHeight($row, $height); - } return $this; @@ -815,22 +865,23 @@ public function setAutoSize($columns = false) $this->autoSize = $columns ? $columns : false; // If is not an array - if(!is_array($columns) && $columns) + if (!is_array($columns) && $columns) { // Get the highest column $toCol = $this->getHighestColumn(); // Lop through the columns and set the auto size $toCol++; - for ($i = 'A'; $i !== $toCol; $i++) { + for ($i = 'A'; $i !== $toCol; $i++) + { $this->getColumnDimension($i)->setAutoSize(true); } } // Set autosize for the given columns - elseif(is_array($columns)) + elseif (is_array($columns)) { - foreach($columns as $column) + foreach ($columns as $column) { $this->getColumnDimension($column)->setAutoSize(true); } @@ -848,7 +899,7 @@ public function setAutoSize($columns = false) */ public function getAutosize() { - if(isset($this->autoSize)) + if (isset($this->autoSize)) return $this->autoSize; return Config::get('excel::export.autosize', true); @@ -872,17 +923,19 @@ public function setAutoFilter($value = false) { $value = $value ? $value : $this->calculateWorksheetDimension(); parent::setAutoFilter($value); + return $this; } /** * Freeze or lock rows and columns - * @param string $pane rows and columns - * @return LaravelExcelWorksheet + * @param string $pane rows and columns + * @return LaravelExcelWorksheet */ public function setFreeze($pane = 'A2') { $this->freezePane($pane); + return $this; } @@ -893,6 +946,7 @@ public function setFreeze($pane = 'A2') public function freezeFirstRow() { $this->setFreeze('A2'); + return $this; } @@ -903,6 +957,7 @@ public function freezeFirstRow() public function freezeFirstColumn() { $this->setFreeze('B1'); + return $this; } @@ -913,40 +968,41 @@ public function freezeFirstColumn() public function freezeFirstRowAndColumn() { $this->setFreeze('B2'); + return $this; } /** * Set a range of cell borders - * @param string $pane Start and end of the cell (A1:F10) - * @param string $weight Border style - * @return LaravelExcelWorksheet + * @param string $pane Start and end of the cell (A1:F10) + * @param string $weight Border style + * @return LaravelExcelWorksheet */ public function setBorder($pane = 'A1', $weight = 'thin') { // Set all borders $this->getStyle($pane) - ->getBorders() - ->getAllBorders() - ->setBorderStyle($weight); + ->getBorders() + ->getAllBorders() + ->setBorderStyle($weight); return $this; } /** * Set all cell borders - * @param string $weight Border style (Reference setBorder style list) - * @return LaravelExcelWorksheet + * @param string $weight Border style (Reference setBorder style list) + * @return LaravelExcelWorksheet */ public function setAllBorders($weight = 'thin') { - $styleArray = array( - 'borders' => array( - 'allborders' => array( + $styleArray = [ + 'borders' => [ + 'allborders' => [ 'style' => $weight - ) - ) - ); + ] + ] + ]; // Apply the style $this->getDefaultStyle() @@ -957,13 +1013,15 @@ public function setAllBorders($weight = 'thin') /** * Set the cell format of the column - * @param array $formats An array of cells you want to format columns - * @return LaravelExcelWorksheet + * @param array $formats An array of cells you want to format columns + * @return LaravelExcelWorksheet */ - public function setColumnFormat(Array $formats){ + public function setColumnFormat(Array $formats) + { // Loop through the columns - foreach ($formats as $column => $format) { + foreach ($formats as $column => $format) + { // Change the format for a specific cell or range $this->getStyle($column) @@ -985,7 +1043,8 @@ public function mergeCells($pRange = 'A1:A1', $alignment = false) parent::mergeCells($pRange); // Set center alignment on merge cells - $this->cells($pRange, function($cell) use ($alignment) { + $this->cells($pRange, function ($cell) use ($alignment) + { $aligment = is_string($alignment) ? $alignment : Config::get('excel::export.merged_cell_alignment', 'left'); $cell->setAlignment($aligment); }); @@ -995,14 +1054,16 @@ public function mergeCells($pRange = 'A1:A1', $alignment = false) /** * Set the columns you want to merge - * @return LaravelExcelWorksheet - * @param array $mergeColumn An array of columns you want to merge + * @return LaravelExcelWorksheet + * @param array $mergeColumn An array of columns you want to merge */ public function setMergeColumn(Array $mergeColumn, $alignment = false) { - foreach ($mergeColumn['columns'] as $column) { - foreach ($mergeColumn['rows'] as $row) { - $this->mergeCells($column.$row[0].":".$column.$row[1], $alignment); + foreach ($mergeColumn['columns'] as $column) + { + foreach ($mergeColumn['rows'] as $row) + { + $this->mergeCells($column . $row[0] . ":" . $column . $row[1], $alignment); } } @@ -1015,7 +1076,7 @@ public function setMergeColumn(Array $mergeColumn, $alignment = false) */ protected function getStartRow() { - if($this->getHighestRow() == 1) + if ($this->getHighestRow() == 1) return 1; return $this->getHighestRow() + 1; @@ -1023,7 +1084,7 @@ protected function getStartRow() /** * Return range from row - * @param integer $rowNumber + * @param integer $rowNumber * @return string $range */ protected function rowToRange($rowNumber) @@ -1062,28 +1123,44 @@ protected function getDefaultStrictNullComparison() /** * Dynamically call methods * @param string $method - * @param array $params + * @param array $params * @throws LaravelExcelException * @return LaravelExcelWorksheet */ public function __call($method, $params) { // If the dynamic call starts with "with", add the var to the data array - if(starts_with($method, 'with')) + if (starts_with($method, 'with')) { $key = lcfirst(str_replace('with', '', $method)); $this->_addVars($key, reset($params)); + return $this; } // If it's a setter - elseif(starts_with($method, 'set') ) + elseif (starts_with($method, 'set')) { // set the attribute $this->_setAttributes($method, $params); + return $this; } - throw new LaravelExcelException('[ERROR] Laravel Worksheet method ['. $method .'] does not exist.'); + throw new LaravelExcelException('[ERROR] Laravel Worksheet method [' . $method . '] does not exist.'); + } + + /** + * @param string $cellValue + * @param mixed|null $currentColumn + * @param bool $startRow + * @return \PHPExcel_Cell|\PHPExcel_Worksheet|void + * @throws PHPExcel_Exception + */ + public function setValueOfCell($cellValue, $currentColumn, $startRow) + { + is_numeric($cellValue) && !is_integer($cellValue) + ? $this->getCell($currentColumn . $startRow)->setValueExplicit($cellValue) + : $this->getCell($currentColumn . $startRow)->setValue($cellValue); } } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Collections/ExcelCollection.php b/src/Maatwebsite/Excel/Collections/ExcelCollection.php index 1ab24756d..cbcd56185 100644 --- a/src/Maatwebsite/Excel/Collections/ExcelCollection.php +++ b/src/Maatwebsite/Excel/Collections/ExcelCollection.php @@ -38,5 +38,4 @@ public function setTitle($title) { $this->title = $title; } - } \ No newline at end of file From 9e0140d5d94e7de966f8953057ea169ca3803860 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 20:00:54 +0200 Subject: [PATCH 0210/1332] Add support for wrap-text in views, fixes issue #171 --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 7c195cf76..8a4af72a7 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -1185,6 +1185,19 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) ['style' => $borderStyle, 'color' => ['rgb' => $color]] ); break; + + // wrap-text + case 'wrap-text': + + if($value == 'true') + $wrap = true; + + if(!$value || $value == 'false') + $wrap = false; + + $cells->getAlignment()->setWrapText($wrap); + + break; } } From 1dc57f0f05f69bce6ec080cc958af4adce815d32 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 20:15:35 +0200 Subject: [PATCH 0211/1332] Return null when a date cell is empty, fixes issue #197 --- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 39 +++++++++++-------- .../Excel/Readers/LaravelExcelReader.php | 4 +- 2 files changed, 24 insertions(+), 19 deletions(-) diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 33f61e381..151a9ccd1 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -70,7 +70,7 @@ class ExcelParser { * Columns we want to fetch * @var array */ - protected $columns = array(); + protected $columns = []; /** * Row counter @@ -103,7 +103,7 @@ public function __construct($reader) * @param array $columns * @return SheetCollection */ - public function parseFile($columns = array()) + public function parseFile($columns = []) { // Init new sheet collection $workbook = new SheetCollection(); @@ -174,7 +174,7 @@ protected function parseWorksheet() $this->excel->setActiveSheetIndex($this->w); // Fetch the labels - $this->indices = $this->reader->hasHeading() ? $this->getIndices() : array(); + $this->indices = $this->reader->hasHeading() ? $this->getIndices() : []; // Parse the rows return $this->parseRows(); @@ -190,7 +190,7 @@ protected function getIndices() $this->row = $this->worksheet->getRowIterator(1)->current(); // Set empty labels array - $this->indices = array(); + $this->indices = []; // Loop through the cells foreach ($this->row->getCellIterator() as $this->cell) @@ -384,7 +384,7 @@ protected function hasReachedLimit() protected function parseCells() { $i = 0; - $parsedCells = array(); + $parsedCells = []; // Set the cell iterator $cellIterator = $this->row->getCellIterator(); @@ -468,7 +468,7 @@ protected function getCalculatedValue() protected function encode($value) { // Get input and output encoding - list($input, $output) = array_values(Config::get('excel::import.encoding', array('UTF-8', 'UTF-8'))); + list($input, $output) = array_values(Config::get('excel::import.encoding', ['UTF-8', 'UTF-8'])); // If they are the same, return the value if($input == $output) @@ -503,14 +503,20 @@ protected function parseDate() */ protected function parseDateAsCarbon() { - // Convert excel time to php date object - $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format('Y-m-d H:i:s'); + // If has a date + if($cellContent = $this->cell->getCalculatedValue()) + { + // Convert excel time to php date object + $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format('Y-m-d H:i:s'); + + // Parse with carbon + $date = Carbon::parse($date); - // Parse with carbon - $date = Carbon::parse($date); + // Format the date if wanted + return $this->reader->getDateFormat() ? $date->format($this->reader->getDateFormat()) : $date; + } - // Format the date if wanted - return $this->reader->getDateFormat() ? $date->format($this->reader->getDateFormat()) : $date; + return null; } /** @@ -563,7 +569,7 @@ protected function getIndexFromColumn() * Set selected columns * @param array $columns */ - protected function setSelectedColumns($columns = array()) + protected function setSelectedColumns($columns = []) { // Set the columns $this->columns = $columns; @@ -580,22 +586,21 @@ protected function hasSelectedColumns() /** * Set selected columns - * @param array $columns + * @return array */ protected function getSelectedColumns() { // Set the columns return $this->columns; - } /** * Reset - * @return [type] [description] + * @return void */ protected function reset() { - $this->indices = array(); + $this->indices = []; $this->isParsed = false; } diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index de9df921c..3214b3a27 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -1,9 +1,9 @@ Date: Wed, 10 Sep 2014 20:21:32 +0200 Subject: [PATCH 0212/1332] Support for local tylesheets with http:// , fixes issue #190 --- src/Maatwebsite/Excel/Parsers/CssParser.php | 23 +-------------------- 1 file changed, 1 insertion(+), 22 deletions(-) diff --git a/src/Maatwebsite/Excel/Parsers/CssParser.php b/src/Maatwebsite/Excel/Parsers/CssParser.php index dbb2fd4ce..ebab4190f 100644 --- a/src/Maatwebsite/Excel/Parsers/CssParser.php +++ b/src/Maatwebsite/Excel/Parsers/CssParser.php @@ -229,28 +229,7 @@ protected function getCleanStyleSheetLink($node) // Get the link $link = $node->attributes()->href; - if (substr($link, 0, 4) != 'http') - { - if (substr($link, 0, 1) == '/') { - $link = $this->getUrlScheme() . '://' . $link; - } else { - $link = $this->getUrlScheme() . '://' . dirname($this->getUrlScheme()) . '/' . $link; - } - } - - return $link; - } - - /** - * Get the URL scheme - * @return string - */ - protected function getUrlScheme() - { - if(!$this->scheme) - $this->scheme = parse_url(/service/url::getScheme()); - - return $this->scheme; + return url(http://github.com/$link); } /** From 77ee687c701f8d7a9ec110ee59006b51a1dde7dd Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 20:47:16 +0200 Subject: [PATCH 0213/1332] If a class is used on a tr, use class on all td-children, fixes issue #169 --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 8a4af72a7..1d95dabee 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -32,6 +32,11 @@ */ class Html extends PHPExcel_Reader_HTML { + /** + * @var array + */ + protected $styleForRows = []; + /** * Input encoding * @var string @@ -233,6 +238,10 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & { $attributeArray = []; + // If it's a column, and it's row has a class, style it + if(in_array($row, array_keys($this->styleForRows))) + $this->styleByClass($sheet, $column, $row, $this->styleForRows[$row]); + // Loop through the child's attributes foreach ($child->attributes as $attribute) { @@ -279,6 +288,11 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Classes case 'class': + + // If it's a tr, remember the row number + if($child->nodeName == 'tr') + $this->styleForRows[$row] = $attribute->value; + $this->styleByClass($sheet, $column, $row, $attribute->value); break; @@ -1279,6 +1293,11 @@ private function processMergedCells($sheet, &$column, $row, $cellContent) (PHPExcel_Cell::columnIndexFromString($column) + 1) - 1 ); $column = $newCol; + + // If it's a column, and it's row has a class, style it + if(in_array($row, array_keys($this->styleForRows))) + $this->styleByClass($sheet, $column, $row, $this->styleForRows[$row]); + $this->_flushCell($sheet, $newCol, $row, $cellContent); } } From 7185a81b0a576febf1d5d29612ceb3bbe4c8dab2 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 20:52:57 +0200 Subject: [PATCH 0214/1332] Support for dynamically adding rows to an empty sheet, fixes issue #189 --- .../Excel/Classes/LaravelExcelWorksheet.php | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index f3fd90efd..649ed885d 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -94,6 +94,11 @@ class LaravelExcelWorksheet extends PHPExcel_Worksheet { */ protected $autoGenerateHeading = true; + /** + * @var bool + */ + protected $hasRowsAdded = false; + /** * Create a new worksheet * @@ -199,6 +204,9 @@ public function row($rowNumber, $callback = null) } } + // Remember that we have added rows + $this->hasRowsAdded = true; + return $this; } @@ -1076,7 +1084,7 @@ public function setMergeColumn(Array $mergeColumn, $alignment = false) */ protected function getStartRow() { - if ($this->getHighestRow() == 1) + if ($this->getHighestRow() == 1 && !$this->hasRowsAdded) return 1; return $this->getHighestRow() + 1; From 3e73627433c9e29bf9c6b2eefb2a493d351ad00d Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 21:13:35 +0200 Subject: [PATCH 0215/1332] Codestyle cleanup + update docblocks --- src/Maatwebsite/Excel/Classes/Cache.php | 53 ++- .../Excel/Classes/FormatIdentifier.php | 37 +- .../Excel/Classes/LaravelExcelWorksheet.php | 49 +-- src/Maatwebsite/Excel/Classes/PHPExcel.php | 28 +- .../Excel/Collections/CellCollection.php | 7 +- .../Excel/Collections/ExcelCollection.php | 4 +- .../Excel/Collections/RowCollection.php | 4 +- .../Excel/Collections/SheetCollection.php | 4 +- src/Maatwebsite/Excel/Excel.php | 44 +-- .../Excel/ExcelServiceProvider.php | 342 +++++++++--------- .../Exceptions/LaravelExcelException.php | 4 +- src/Maatwebsite/Excel/Facades/Excel.php | 9 +- src/Maatwebsite/Excel/Parsers/CssParser.php | 47 ++- src/Maatwebsite/Excel/Parsers/ExcelParser.php | 64 ++-- src/Maatwebsite/Excel/Parsers/ViewParser.php | 30 +- src/Maatwebsite/Excel/Readers/Batch.php | 38 +- .../Excel/Readers/ConfigReader.php | 18 +- src/Maatwebsite/Excel/Readers/HtmlReader.php | 22 +- .../Excel/Readers/LaravelExcelReader.php | 143 +++++--- src/Maatwebsite/Excel/Writers/CellWriter.php | 81 ++--- .../Excel/Writers/LaravelExcelWriter.php | 106 +++--- src/config/cache.php | 26 +- src/config/config.php | 70 ++-- src/config/csv.php | 8 +- src/config/export.php | 30 +- src/config/import.php | 40 +- src/config/views.php | 210 +++++------ 27 files changed, 795 insertions(+), 723 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/Cache.php b/src/Maatwebsite/Excel/Classes/Cache.php index 260a49742..e30ad7234 100644 --- a/src/Maatwebsite/Excel/Classes/Cache.php +++ b/src/Maatwebsite/Excel/Classes/Cache.php @@ -16,19 +16,19 @@ class Cache { * Available caching drivers * @var array */ - protected $available = array( - 'memory' => 'cache_in_memory', - 'gzip' => 'cache_in_memory_gzip', - 'serialized' => 'cache_in_memory_serialized', - 'igbinary' => 'cache_igbinary', - 'discISAM' => 'cache_to_discISAM', - 'apc' => 'cache_to_apc', - 'memcache' => 'cache_to_memcache', - 'temp' => 'cache_to_phpTemp', - 'wincache' => 'cache_to_wincache', - 'sqlite' => 'cache_to_sqlite', - 'sqlite3' => 'cache_to_sqlite3' - ); + protected $available = [ + 'memory' => 'cache_in_memory', + 'gzip' => 'cache_in_memory_gzip', + 'serialized' => 'cache_in_memory_serialized', + 'igbinary' => 'cache_igbinary', + 'discISAM' => 'cache_to_discISAM', + 'apc' => 'cache_to_apc', + 'memcache' => 'cache_to_memcache', + 'temp' => 'cache_to_phpTemp', + 'wincache' => 'cache_to_wincache', + 'sqlite' => 'cache_to_sqlite', + 'sqlite3' => 'cache_to_sqlite3' + ]; /** * The name of the config file @@ -42,11 +42,11 @@ class Cache { public function __construct() { // Get driver and settings from the config - $this->driver = Config::get($this->configName . '.driver', 'memory'); - $this->settings = Config::get($this->configName . '.settings', array()); + $this->driver = Config::get($this->configName . '.driver', 'memory'); + $this->settings = Config::get($this->configName . '.settings', []); // Init if caching is enabled - if($this->isEnabled()) + if ($this->isEnabled()) $this->init(); } @@ -69,8 +69,8 @@ public function init() */ public function findDriver() { - $property = $this->detect(); - $this->method = constant($this->class.'::'.$property); + $property = $this->detect(); + $this->method = constant($this->class . '::' . $property); } /** @@ -92,24 +92,24 @@ protected function detect() */ protected function addAdditionalSettings() { - switch($this->driver) + switch ($this->driver) { case 'memcache': // Add extra memcache settings - $this->settings = array_merge($this->settings, array( - 'memcacheServer' => Config::get($this->configName . '.memcache.host', 'localhost'), - 'memcachePort' => Config::get($this->configName . '.memcache.port', 11211) - )); + $this->settings = array_merge($this->settings, [ + 'memcacheServer' => Config::get($this->configName . '.memcache.host', 'localhost'), + 'memcachePort' => Config::get($this->configName . '.memcache.port', 11211) + ]); break; case 'discISAM': // Add dir - $this->settings = array_merge($this->settings, array( - 'dir' => Config::get($this->configName . '.dir', storage_path('cache')), - )); + $this->settings = array_merge($this->settings, [ + 'dir' => Config::get($this->configName . '.dir', storage_path('cache')), + ]); break; } @@ -123,5 +123,4 @@ public function isEnabled() { return Config::get($this->configName . '.enable', true) ? true : false; } - } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Classes/FormatIdentifier.php b/src/Maatwebsite/Excel/Classes/FormatIdentifier.php index 134c4035d..57696a2e9 100644 --- a/src/Maatwebsite/Excel/Classes/FormatIdentifier.php +++ b/src/Maatwebsite/Excel/Classes/FormatIdentifier.php @@ -12,7 +12,7 @@ class FormatIdentifier { * @var array * @access protected */ - protected $formats = array( + protected $formats = [ 'Excel2007', 'Excel5', 'Excel2003XML', @@ -21,11 +21,11 @@ class FormatIdentifier { 'Gnumeric', 'CSV', 'HTML', - ); + ]; /** * Construct new format identifier - * @param FileSystem $files + * @param Filesystem $filesystem */ public function __construct(Filesystem $filesystem) { @@ -34,6 +34,8 @@ public function __construct(Filesystem $filesystem) /** * Get the file format by file + * @param $file + * @throws LaravelExcelException * @return string $format */ public function getFormatByFile($file) @@ -45,7 +47,7 @@ public function getFormatByFile($file) $format = $this->getFormatByExtension($ext); // Check if the file can be read - if($this->canRead($format, $file)) + if ($this->canRead($format, $file)) return $format; // Do a last try to init the file with all available readers @@ -54,11 +56,13 @@ public function getFormatByFile($file) /** * Identify file format + * @param $ext * @return string $format */ public function getFormatByExtension($ext) { - switch($ext) { + switch ($ext) + { /* |-------------------------------------------------------------------------- @@ -157,7 +161,7 @@ public function getFormatByExtension($ext) */ public function getContentTypeByFormat($format) { - switch($format) + switch ($format) { /* @@ -166,7 +170,7 @@ public function getContentTypeByFormat($format) |-------------------------------------------------------------------------- */ case 'Excel2007': - return'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'; + return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'; break; /* @@ -175,7 +179,7 @@ public function getContentTypeByFormat($format) |-------------------------------------------------------------------------- */ case 'Excel5': - return'application/vnd.ms-excel; charset=UTF-8'; + return 'application/vnd.ms-excel; charset=UTF-8'; break; /* @@ -193,7 +197,7 @@ public function getContentTypeByFormat($format) |-------------------------------------------------------------------------- */ case 'CSV': - return'application/csv; charset=UTF-8'; + return 'application/csv; charset=UTF-8'; break; /* @@ -209,6 +213,9 @@ public function getContentTypeByFormat($format) /** * Try every reader we have + * @param $file + * @param bool $wrongFormat + * @throws LaravelExcelException * @return string $format */ protected function lastResort($file, $wrongFormat = false) @@ -217,23 +224,26 @@ protected function lastResort($file, $wrongFormat = false) foreach ($this->formats as $format) { // Check if the file could be read - if($wrongFormat != $format && $this->canRead($format, $file)) + if ($wrongFormat != $format && $this->canRead($format, $file)) return $format; } // Give up searching and throw an exception - throw new LaravelExcelException('[ERROR] Reader could not identify file format for file ['. $file .'] with extension [' . $ext . ']'); + throw new LaravelExcelException('[ERROR] Reader could not identify file format for file [' . $file . '] with extension [' . $ext . ']'); } /** * Check if we can read the file + * @param $format + * @param $file * @return boolean */ protected function canRead($format, $file) { - if($format) + if ($format) { $reader = $this->initReader($format); + return $reader && $reader->canRead($file); } @@ -243,7 +253,7 @@ protected function canRead($format, $file) /** * Init the reader based on the format * @param string $format - * @return Reader + * @return \PHPExcel_Reader_IReader */ protected function initReader($format) { @@ -259,5 +269,4 @@ protected function getExtension($file) { return strtolower($this->filesystem->extension($file)); } - } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 649ed885d..6c0590c40 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -8,6 +8,7 @@ use Illuminate\Support\Facades\Config; use Maatwebsite\Excel\Writers\CellWriter; use Maatwebsite\Excel\Exceptions\LaravelExcelException; +use PHPExcel_Worksheet_PageSetup; /** * @@ -274,7 +275,7 @@ public function appendRow($rowNumber = 1, $callback = null) /** * Manipulate a single cell * @param array|string $cell - * @param callback $callback + * @param bool|callable $callback $callback * @return LaravelExcelWorksheet */ public function cell($cell, $callback = false) @@ -292,8 +293,8 @@ public function cell($cell, $callback = false) /** * Manipulate a cell or a range of cells - * @param array $cells - * @param callback $callback + * @param array $cells + * @param bool|callable $callback $callback * @return LaravelExcelWorksheet */ public function cells($cells, $callback = false) @@ -310,9 +311,6 @@ public function cells($cells, $callback = false) /** * Load a View and convert to HTML - * @param string $view - * @param array $data - * @param array $mergeData * @return LaravelExcelWorksheet */ public function setView() @@ -386,9 +384,9 @@ public function parsed() /** * Set data for the current sheet - * @param string $keys - * @param string $value - * @param boolean $headingGeneration + * @param $key + * @param bool|string $value + * @param boolean $headingGeneration * @return LaravelExcelWorksheet */ public function with($key, $value = false, $headingGeneration = true) @@ -405,7 +403,11 @@ public function with($key, $value = false, $headingGeneration = true) /** * From array * @param Collection|array $source + * @param null $nullValue + * @param bool $startCell + * @param bool $strictNullComparison * @param boolean $headingGeneration + * @throws PHPExcel_Exception * @return LaravelExcelWorksheet */ public function fromModel($source = null, $nullValue = null, $startCell = false, $strictNullComparison = false, $headingGeneration = true) @@ -416,10 +418,11 @@ public function fromModel($source = null, $nullValue = null, $startCell = false, /** * Fill worksheet from values in array * - * @param array $source Source array - * @param mixed $nullValue Value in source array that stands for blank cell - * @param string $startCell Insert array starting from this cell address as the top left coordinate - * @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array + * @param array $source Source array + * @param mixed $nullValue Value in source array that stands for blank cell + * @param bool|string $startCell Insert array starting from this cell address as the top left coordinate + * @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array + * @param bool $headingGeneration * @throws PHPExcel_Exception * @return LaravelExcelWorksheet */ @@ -484,8 +487,9 @@ public function fromArray($source = null, $nullValue = null, $startCell = false, /** * Add vars to the data array - * @param string $key - * @param string $value + * @param string $key + * @param bool|string $value + * @throws PHPExcel_Exception * @return void */ protected function _addVars($key, $value = false) @@ -627,8 +631,9 @@ protected function generateHeadingByIndices() /** * Set attributes - * @param string $key + * @param $setter * @param array|string $params + * @throws LaravelExcelException * @return void|PHPExcel_Worksheet_PageSetup */ public function _setAttributes($setter, $params) @@ -660,7 +665,7 @@ public function _setAttributes($setter, $params) * @param string $setter * @param string $key * @param array|string $params - * @return PHPExcel_Style + * @return PHPExcel_Style */ protected function setDefaultStyles($setter, $key, $params) { @@ -703,12 +708,11 @@ public function setFont($fonts) /** * Set default font styles * @param string $caller - * @param string $setter * @param string $key * @param array|string $params * @return PHPExcel_Style */ - protected function setFontStyle($caller, $setter, $key, $params) + protected function setFontStyle($caller, $key, $params) { // Set caller to font $caller = $caller->getFont(); @@ -829,8 +833,8 @@ public function setHeight($row, $value = false) /** * Set cell size * @param array|string $cell - * @param integer $width - * @param integer $height + * @param bool $width + * @param bool|int $height * @return LaravelExcelWorksheet */ public function setSize($cell, $width = false, $height = false) @@ -1043,6 +1047,8 @@ public function setColumnFormat(Array $formats) /** * Merge cells * @param string $pRange + * @param bool $alignment + * @throws PHPExcel_Exception * @return LaravelExcelWorksheet */ public function mergeCells($pRange = 'A1:A1', $alignment = false) @@ -1064,6 +1070,7 @@ public function mergeCells($pRange = 'A1:A1', $alignment = false) * Set the columns you want to merge * @return LaravelExcelWorksheet * @param array $mergeColumn An array of columns you want to merge + * @param bool $alignment */ public function setMergeColumn(Array $mergeColumn, $alignment = false) { diff --git a/src/Maatwebsite/Excel/Classes/PHPExcel.php b/src/Maatwebsite/Excel/Classes/PHPExcel.php index 822b583b3..46dd5915c 100644 --- a/src/Maatwebsite/Excel/Classes/PHPExcel.php +++ b/src/Maatwebsite/Excel/Classes/PHPExcel.php @@ -8,20 +8,19 @@ * Laravel wrapper for PHPExcel * * @category Laravel Excel - * @version 1.0.0 * @package maatwebsite/excel * @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl) * @copyright Original Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) * @author Maatwebsite * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class PHPExcel extends PHPOffice_PHPExcel -{ +class PHPExcel extends PHPOffice_PHPExcel { + /** * Allowed autofill properties * @var array */ - public $allowedProperties = array( + public $allowedProperties = [ 'creator', 'lastModifiedBy', 'description', @@ -30,17 +29,17 @@ class PHPExcel extends PHPOffice_PHPExcel 'category', 'manager', 'company' - ); + ]; /** * Create sheet and add it to this workbook * - * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) - * @param string $title + * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) + * @param bool|string $title + * @throws \PHPExcel_Exception * @return LaravelExcelWorksheet - * @throws PHPExcel_Exception */ - public function createSheet($iSheetIndex = NULL, $title = false) + public function createSheet($iSheetIndex = null, $title = false) { // Init new Laravel Excel worksheet $newSheet = new LaravelExcelWorksheet($this, $title); @@ -54,14 +53,14 @@ public function createSheet($iSheetIndex = NULL, $title = false) /** * Check if the user change change the workbook property - * @param string $method + * @param string $method * @return boolean */ public function isChangeableProperty($method) { $name = lcfirst(str_replace('set', '', $method)); - return in_array($name, $this->getAllowedProperties()) ? true : false; + return in_array($name, $this->getAllowedProperties()) ? true : false; } /** @@ -75,16 +74,16 @@ public function setDefaultProperties($custom) $properties = $this->getProperties(); // Get fillable properties - foreach($this->getAllowedProperties() as $prop) + foreach ($this->getAllowedProperties() as $prop) { // Get the method $method = 'set' . ucfirst($prop); // get the value - $value = in_array($prop, array_keys($custom)) ? $custom[$prop] : Config::get('excel::properties.' . $prop, NULL); + $value = in_array($prop, array_keys($custom)) ? $custom[$prop] : Config::get('excel::properties.' . $prop, null); // set the property - call_user_func_array(array($properties, $method), array($value)); + call_user_func_array([$properties, $method], [$value]); } } @@ -96,5 +95,4 @@ public function getAllowedProperties() { return $this->allowedProperties; } - } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Collections/CellCollection.php b/src/Maatwebsite/Excel/Collections/CellCollection.php index a350eb182..f1edf1513 100644 --- a/src/Maatwebsite/Excel/Collections/CellCollection.php +++ b/src/Maatwebsite/Excel/Collections/CellCollection.php @@ -29,9 +29,9 @@ public function __construct(array $items = []) */ public function setItems($items) { - foreach($items as $name => $value) + foreach ($items as $name => $value) { - if($name) + if ($name) $this->put($name, $value || is_numeric($value) ? $value : null); } } @@ -43,8 +43,7 @@ public function setItems($items) */ public function __get($key) { - if($this->has($key)) + if ($this->has($key)) return $this->get($key); } - } diff --git a/src/Maatwebsite/Excel/Collections/ExcelCollection.php b/src/Maatwebsite/Excel/Collections/ExcelCollection.php index cbcd56185..2bd3424bd 100644 --- a/src/Maatwebsite/Excel/Collections/ExcelCollection.php +++ b/src/Maatwebsite/Excel/Collections/ExcelCollection.php @@ -23,7 +23,7 @@ class ExcelCollection extends Collection { /** * Get the title - * @return [type] [description] + * @return string */ public function getTitle() { @@ -32,7 +32,7 @@ public function getTitle() /** * Set the title - * @param [type] $title [description] + * @param $title */ public function setTitle($title) { diff --git a/src/Maatwebsite/Excel/Collections/RowCollection.php b/src/Maatwebsite/Excel/Collections/RowCollection.php index 06af4aab4..5f572f121 100644 --- a/src/Maatwebsite/Excel/Collections/RowCollection.php +++ b/src/Maatwebsite/Excel/Collections/RowCollection.php @@ -11,4 +11,6 @@ * @author Maatwebsite * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class RowCollection extends ExcelCollection {} \ No newline at end of file +class RowCollection extends ExcelCollection { + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Collections/SheetCollection.php b/src/Maatwebsite/Excel/Collections/SheetCollection.php index 55e7bb7b0..9c95d97d0 100644 --- a/src/Maatwebsite/Excel/Collections/SheetCollection.php +++ b/src/Maatwebsite/Excel/Collections/SheetCollection.php @@ -11,4 +11,6 @@ * @author Maatwebsite * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class SheetCollection extends ExcelCollection {} \ No newline at end of file +class SheetCollection extends ExcelCollection { + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Excel.php b/src/Maatwebsite/Excel/Excel.php index 3627ed2ad..8e2f75b98 100644 --- a/src/Maatwebsite/Excel/Excel.php +++ b/src/Maatwebsite/Excel/Excel.php @@ -18,8 +18,8 @@ * @author Maatwebsite * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class Excel -{ +class Excel { + /** * Excel object * @var PHPExcel @@ -40,7 +40,7 @@ class Excel /** * Construct Excel - * @param PHPExcel $excel + * @param PHPExcel $excel * @param LaravelExcelReader $reader * @param LaravelExcelWriter $writer */ @@ -54,7 +54,7 @@ public function __construct(PHPExcel $excel, LaravelExcelReader $reader, Laravel /** * Create a new file - * @param string $title + * @param $filename * @param callable|null $callback * @return LaravelExcelWriter */ @@ -74,7 +74,7 @@ public function create($filename, $callback = null) $writer->setTitle($filename); // Do the callback - if($callback instanceof Closure) + if ($callback instanceof Closure) call_user_func($callback, $writer); // Return the writer object @@ -85,10 +85,10 @@ public function create($filename, $callback = null) * * Load an existing file * - * @param string $file The file we want to load - * @param callback|null $callback - * @param string|null $encoding - * @return LaravelExcelReader + * @param string $file The file we want to load + * @param callback|null $callback + * @param string|null $encoding + * @return LaravelExcelReader * */ public function load($file, $callback = null, $encoding = null) @@ -106,7 +106,7 @@ public function load($file, $callback = null, $encoding = null) $reader->load($file, $encoding); // Do the callback - if($callback instanceof Closure) + if ($callback instanceof Closure) call_user_func($callback, $reader); // Return the reader object @@ -118,34 +118,37 @@ public function load($file, $callback = null, $encoding = null) * @param $sheets * @return LaravelExcelReader */ - public function selectSheets($sheets = array()) + public function selectSheets($sheets = []) { $sheets = is_array($sheets) ? $sheets : func_get_args(); $this->reader->setSelectedSheets($sheets); + return $this; } /** * Select sheets by index - * @param [type] $sheets [description] - * @return [type] [description] + * @param array $sheets + * @return $this */ - public function selectSheetsByIndex($sheets = array()) + public function selectSheetsByIndex($sheets = []) { $sheets = is_array($sheets) ? $sheets : func_get_args(); $this->reader->setSelectedSheetIndices($sheets); + return $this; } /** * Batch import - * @param $files + * @param $files * @param callback $callback * @return PHPExcel */ public function batch($files, Closure $callback) { $batch = new Batch; + return $batch->start($this, $files, $callback); } @@ -156,7 +159,7 @@ public function batch($files, Closure $callback) * @param array $mergeData * @return LaravelExcelWriter */ - public function shareView($view, $data = array(), $mergeData = array()) + public function shareView($view, $data = [], $mergeData = []) { return $this->create($view)->shareView($view, $data, $mergeData); } @@ -168,7 +171,7 @@ public function shareView($view, $data = array(), $mergeData = array()) * @param array $mergeData * @return LaravelExcelWriter */ - public function loadView($view, $data = array(), $mergeData = array()) + public function loadView($view, $data = [], $mergeData = []) { return $this->shareView($view, $data, $mergeData); } @@ -180,13 +183,12 @@ public function loadView($view, $data = array(), $mergeData = array()) public function __call($method, $params) { // If the dynamic call starts with "with", add the var to the data array - if(method_exists($this->excel, $method)) + if (method_exists($this->excel, $method)) { // Call the method from the excel object with the given params - return call_user_func_array(array($this->excel, $method), $params); + return call_user_func_array([$this->excel, $method], $params); } - throw new LaravelExcelException('Laravel Excel method ['. $method .'] does not exist'); + throw new LaravelExcelException('Laravel Excel method [' . $method . '] does not exist'); } - } diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index a8f93f81e..e36a25f4d 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -26,177 +26,179 @@ */ class ExcelServiceProvider extends ServiceProvider { - /** - * Indicates if loading of the provider is deferred. - * - * @var bool - */ - protected $defer = false; - - /** - * Bootstrap the application events. - * - * @return void - */ - - public function boot() - { - // Boot the package - $this->package('maatwebsite/excel'); - - // Set the autosizing settings - $this->setAutoSizingSettings(); - } - - /** - * Register the service provider. - * - * @return void - */ - public function register() - { - $this->bindClasses(); - $this->bindReaders(); - $this->bindParsers(); - $this->bindPHPExcelClass(); - $this->bindWriters(); - $this->bindExcel(); - } - - /** - * Bind PHPExcel classes - * @return void - */ - protected function bindPHPExcelClass() - { - // Set object - $me = $this; - - // Bind the PHPExcel class - $this->app['phpexcel'] = $this->app->share(function($app) use($me) { - - // Set locale - $me->setLocale(); - - // Set the caching settings - $me->setCacheSettings(); - - // Init phpExcel - return new PHPExcel(); - }); - } - - /** - * Bind writers - * @return void - */ - protected function bindReaders() - { - // Bind the laravel excel reader - $this->app['excel.reader'] = $this->app->share(function($app) - { - return new LaravelExcelReader($app['files'], $app['excel.identifier']); - }); - - // Bind the html reader class - $this->app['excel.readers.html'] = $this->app->share(function($app) - { - return new Html(); - }); - } - - /** - * Bind writers - * @return void - */ - protected function bindParsers() - { - // Bind the view parser - $this->app['excel.parsers.view'] = $this->app->share(function($app) - { - return new ViewParser($app['excel.readers.html']); - }); - } - - /** - * Bind writers - * @return void - */ - protected function bindWriters() - { - // Bind the excel writer - $this->app['excel.writer'] = $this->app->share(function($app) - { - return new LaravelExcelWriter($app->make('Response'), $app['files'], $app['excel.identifier']); - }); - } - - /** - * Bind Excel class - * @return void - */ - protected function bindExcel() - { - // Bind the Excel class and inject its dependencies - $this->app['excel'] = $this->app->share(function($app) + /** + * Indicates if loading of the provider is deferred. + * + * @var bool + */ + protected $defer = false; + + /** + * Bootstrap the application events. + * + * @return void + */ + + public function boot() + { + // Boot the package + $this->package('maatwebsite/excel'); + + // Set the autosizing settings + $this->setAutoSizingSettings(); + } + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + $this->bindClasses(); + $this->bindReaders(); + $this->bindParsers(); + $this->bindPHPExcelClass(); + $this->bindWriters(); + $this->bindExcel(); + } + + /** + * Bind PHPExcel classes + * @return void + */ + protected function bindPHPExcelClass() + { + // Set object + $me = $this; + + // Bind the PHPExcel class + $this->app['phpexcel'] = $this->app->share(function ($app) use ($me) + { + + // Set locale + $me->setLocale(); + + // Set the caching settings + $me->setCacheSettings(); + + // Init phpExcel + return new PHPExcel(); + }); + } + + /** + * Bind writers + * @return void + */ + protected function bindReaders() + { + // Bind the laravel excel reader + $this->app['excel.reader'] = $this->app->share(function ($app) + { + return new LaravelExcelReader($app['files'], $app['excel.identifier']); + }); + + // Bind the html reader class + $this->app['excel.readers.html'] = $this->app->share(function ($app) + { + return new Html(); + }); + } + + /** + * Bind writers + * @return void + */ + protected function bindParsers() + { + // Bind the view parser + $this->app['excel.parsers.view'] = $this->app->share(function ($app) + { + return new ViewParser($app['excel.readers.html']); + }); + } + + /** + * Bind writers + * @return void + */ + protected function bindWriters() + { + // Bind the excel writer + $this->app['excel.writer'] = $this->app->share(function ($app) + { + return new LaravelExcelWriter($app->make('Response'), $app['files'], $app['excel.identifier']); + }); + } + + /** + * Bind Excel class + * @return void + */ + protected function bindExcel() + { + // Bind the Excel class and inject its dependencies + $this->app['excel'] = $this->app->share(function ($app) { return new Excel($app['phpexcel'], $app['excel.reader'], $app['excel.writer'], $app['excel.parsers.view']); }); - } - - /** - * Bind other classes - * @return void - */ - protected function bindClasses() - { - // Bind the format identifier - $this->app['excel.identifier'] = $this->app->share(function($app) { - return new FormatIdentifier($app['files']); - }); - } - - /** - * Set cache settings - * @return Maatwebsite\Excel\Classes\Cache - */ - public function setCacheSettings() - { - return new Cache(); - } - - /** - * Set locale - */ - public function setLocale() - { - $locale = Config::get('app.locale', 'en_us'); - PHPExcel_Settings::setLocale($locale); - } - - /** - * Set the autosizing settings - */ - public function setAutoSizingSettings() - { - $method = Config::get('excel::export.autosize-method', PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX); - PHPExcel_Shared_Font::setAutoSizeMethod($method); - } - - /** - * Get the services provided by the provider. - * - * @return array - */ - public function provides() - { - return array( - 'excel', - 'phpexcel', - 'excel.reader', - 'excel.readers.html', - 'excel.parsers.view', - 'excel.writer' - ); - } + } + + /** + * Bind other classes + * @return void + */ + protected function bindClasses() + { + // Bind the format identifier + $this->app['excel.identifier'] = $this->app->share(function ($app) + { + return new FormatIdentifier($app['files']); + }); + } + + /** + * Set cache settings + * @return Maatwebsite\Excel\Classes\Cache + */ + public function setCacheSettings() + { + return new Cache(); + } + + /** + * Set locale + */ + public function setLocale() + { + $locale = Config::get('app.locale', 'en_us'); + PHPExcel_Settings::setLocale($locale); + } + + /** + * Set the autosizing settings + */ + public function setAutoSizingSettings() + { + $method = Config::get('excel::export.autosize-method', PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX); + PHPExcel_Shared_Font::setAutoSizeMethod($method); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides() + { + return [ + 'excel', + 'phpexcel', + 'excel.reader', + 'excel.readers.html', + 'excel.parsers.view', + 'excel.writer' + ]; + } } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php b/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php index 965faa9f9..2c85eae78 100644 --- a/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php +++ b/src/Maatwebsite/Excel/Exceptions/LaravelExcelException.php @@ -13,4 +13,6 @@ * @author Maatwebsite * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL */ -class LaravelExcelException extends PHPExcel_Exception {} \ No newline at end of file +class LaravelExcelException extends PHPExcel_Exception { + +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Facades/Excel.php b/src/Maatwebsite/Excel/Facades/Excel.php index 96745ac11..395ecfcfc 100644 --- a/src/Maatwebsite/Excel/Facades/Excel.php +++ b/src/Maatwebsite/Excel/Facades/Excel.php @@ -19,9 +19,8 @@ class Excel extends Facade { * Return facade accessor * @return string */ - protected static function getFacadeAccessor() - { - return 'excel'; - } - + protected static function getFacadeAccessor() + { + return 'excel'; + } } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Parsers/CssParser.php b/src/Maatwebsite/Excel/Parsers/CssParser.php index ebab4190f..21ee51027 100644 --- a/src/Maatwebsite/Excel/Parsers/CssParser.php +++ b/src/Maatwebsite/Excel/Parsers/CssParser.php @@ -19,7 +19,7 @@ class CssParser { * Parsed results * @var array */ - protected $results = array(); + protected $results = []; /** * Preg match stringmake @@ -29,13 +29,13 @@ class CssParser { /** * Document DOM - * @var domDocument + * @var \DOMNode */ public $dom; /** * DOM xml - * @var SimpleXMLElement + * @var \SimpleXMLElement */ protected $xml; @@ -43,7 +43,7 @@ class CssParser { * Style sheet links * @var array */ - protected $links = array(); + protected $links = []; /** * Url scheme @@ -53,8 +53,8 @@ class CssParser { /** * Construct the view parser - * @param domDocument $dom - * @return void + * @param \domDocument $dom + * @return \Maatwebsite\Excel\Parsers\CssParser */ public function __construct($dom) { @@ -70,7 +70,7 @@ public function __construct($dom) */ public function lookup($type, $name) { - switch($type) + switch ($type) { case 'id': $name = '#' . $name; @@ -85,10 +85,10 @@ public function lookup($type, $name) $results = $this->toArray(); // Return the css if known - if(isset($results[$name])) + if (isset($results[$name])) return $results[$name]; - return array(); + return []; } /** @@ -112,15 +112,15 @@ protected function findStyleSheets() // Get all stylesheet tags $tags = $this->getStyleSheetTags(); - foreach($tags as $node) + foreach ($tags as $node) { $this->links[] = $this->getCleanStyleSheetLink($node); } // We don't need duplicate css files $this->links = array_unique($this->links); - return $this; + return $this; } /** @@ -129,9 +129,9 @@ protected function findStyleSheets() */ protected function parse() { - foreach($this->links as $link) + foreach ($this->links as $link) { - $css = $this->getCssFromLink($link); + $css = $this->getCssFromLink($link); $this->breakCSSToPHP($css); } } @@ -143,13 +143,13 @@ protected function parse() */ protected function breakCSSToPHP($css) { - $results = array(); + $results = []; preg_match_all($this->matcher, $css, $matches); - foreach($matches[0] as $i => $original) + foreach ($matches[0] as $i => $original) { - if(!starts_with($original, '@')) // ignore attributes starting with @ (like @import) + if (!starts_with($original, '@')) // ignore attributes starting with @ (like @import) $this->breakIntoAttributes($i, $matches); } } @@ -157,7 +157,7 @@ protected function breakCSSToPHP($css) /** * Break css into attributes * @param integer $i - * @param array $mathces + * @param array $matches * @return void */ protected function breakIntoAttributes($i, $matches) @@ -165,23 +165,22 @@ protected function breakIntoAttributes($i, $matches) // Seperate attributes $attributes = explode(';', $matches[2][$i]); - foreach($attributes as $attribute) + foreach ($attributes as $attribute) { $this->breakIntoProperties($attribute, $i, $matches); } - } /** * Break into css properties - * @param string $attribute + * @param string $attribute * @param integer $i - * @param array $matches + * @param array $matches * @return void */ protected function breakIntoProperties($attribute, $i, $matches) { - if (strlen(trim($attribute)) > 0 ) // for missing semicolon on last element, which is legal + if (strlen(trim($attribute)) > 0) // for missing semicolon on last element, which is legal { // List properties with name and value list($name, $value) = explode(':', $attribute); @@ -198,6 +197,7 @@ protected function cleanValue($value) { $value = trim($value); $value = str_replace('!important', '', $value); + return trim($value); } @@ -207,7 +207,7 @@ protected function cleanValue($value) */ protected function importDom() { - return $this->xml = simplexml_import_dom($this->dom); + return $this->xml = simplexml_import_dom($this->dom); } /** @@ -241,5 +241,4 @@ protected function getCssFromLink($link) { return file_get_contents($link); } - } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Parsers/ExcelParser.php b/src/Maatwebsite/Excel/Parsers/ExcelParser.php index 151a9ccd1..56499bf51 100644 --- a/src/Maatwebsite/Excel/Parsers/ExcelParser.php +++ b/src/Maatwebsite/Excel/Parsers/ExcelParser.php @@ -87,7 +87,7 @@ class ExcelParser { /** * Construct excel parser * @param LaravelExcelReader $reader - * @return void + * @return \Maatwebsite\Excel\Parsers\ExcelParser */ public function __construct($reader) { @@ -100,8 +100,8 @@ public function __construct($reader) /** * Parse the file - * @param array $columns - * @return SheetCollection + * @param array $columns + * @return SheetCollection */ public function parseFile($columns = []) { @@ -112,7 +112,7 @@ public function parseFile($columns = []) $this->setSelectedColumns($columns); // If not parsed yet - if(!$this->isParsed) + if (!$this->isParsed) { // Set worksheet count $this->w = 0; @@ -121,16 +121,16 @@ public function parseFile($columns = []) $iterator = $this->excel->getWorksheetIterator(); // Loop through the worksheets - foreach($iterator as $this->worksheet) + foreach ($iterator as $this->worksheet) { // Check if the sheet might have been selected by it's index - if($this->reader->isSelectedByIndex($iterator->key() )) + if ($this->reader->isSelectedByIndex($iterator->key())) { // Parse the worksheet $worksheet = $this->parseWorksheet(); // If multiple sheets - if($this->parseAsMultiple()) + if ($this->parseAsMultiple()) { // Push every sheet $workbook->push($worksheet); @@ -160,8 +160,8 @@ public function parseFile($columns = []) */ protected function parseAsMultiple() { - return ( $this->excel->getSheetCount() > 1 && count($this->reader->getSelectedSheetIndices()) !== 1 ) - || Config::get('excel::import.force_sheets_collection', false); + return ($this->excel->getSheetCount() > 1 && count($this->reader->getSelectedSheetIndices()) !== 1) + || Config::get('excel::import.force_sheets_collection', false); } /** @@ -182,7 +182,7 @@ protected function parseWorksheet() /** * Get the indices - * @return array + * @return array */ protected function getIndices() { @@ -214,9 +214,9 @@ protected function getIndex($cell) $config = $config === true ? 'slugged' : $config; // Get value - $value = $this->getOriginalIndex($cell); + $value = $this->getOriginalIndex($cell); - switch($config) + switch ($config) { case 'slugged': return $this->getSluggedIndex($value, Config::get('excel::import.to_ascii', true)); @@ -243,26 +243,27 @@ protected function getIndex($cell) /** * Get slugged index * @param string $value + * @param bool $ascii * @return string */ protected function getSluggedIndex($value, $ascii = false) { // Get original - $separator = $this->reader->getSeparator(); + $separator = $this->reader->getSeparator(); // Convert to ascii when needed - if($ascii) + if ($ascii) $value = $this->getAsciiIndex($value); // Convert all dashes/underscores into separator $flip = $separator == '-' ? '_' : '-'; - $value = preg_replace('!['.preg_quote($flip).']+!u', $separator, $value); + $value = preg_replace('![' . preg_quote($flip) . ']+!u', $separator, $value); // Remove all characters that are not the separator, letters, numbers, or whitespace. - $value = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($value)); + $value = preg_replace('![^' . preg_quote($separator) . '\pL\pN\s]+!u', '', mb_strtolower($value)); // Replace all separator characters and whitespace by a single separator - $value = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $value); + $value = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $value); return trim($value, $separator); } @@ -299,7 +300,7 @@ protected function getTranslatedIndex($value) /** * Get orignal indice - * @param string $value + * @param $cell * @return string */ protected function getOriginalIndex($cell) @@ -309,7 +310,7 @@ protected function getOriginalIndex($cell) /** * Parse the rows - * @return RowCollection + * @return RowCollection */ protected function parseRows() { @@ -326,7 +327,7 @@ protected function parseRows() foreach ($this->worksheet->getRowIterator($startRow) as $this->row) { // Limit the results when needed - if($this->hasReachedLimit()) + if ($this->hasReachedLimit()) break; // Push the parsed cells inside the parsed rows @@ -350,14 +351,14 @@ protected function getStartRow() $startRow = $this->defaultStartRow; // If the reader has a heading, skip the first row - if($this->reader->hasHeading()) + if ($this->reader->hasHeading()) $startRow++; // Get the amount of rows to skip $skip = $this->reader->getSkip(); // If we want to skip rows, add the amount of rows - if($skip > 0) + if ($skip > 0) $startRow = $startRow + $skip; // Return the startrow @@ -393,17 +394,17 @@ protected function parseCells() $cellIterator->setIterateOnlyExistingCells($this->reader->needsIgnoreEmpty()); // Foreach cells - foreach ($cellIterator as $this->cell) { + foreach ($cellIterator as $this->cell) + { // Check how we need to save the parsed array $index = ($this->reader->hasHeading() && isset($this->indices[$i])) ? $this->indices[$i] : $this->getIndexFromColumn(); // Check if we want to select this column - if($this->cellNeedsParsing($index) ) + if ($this->cellNeedsParsing($index)) { // Set the value $parsedCells[$index] = $this->parseCell($index); - } $i++; @@ -421,14 +422,14 @@ protected function parseCells() protected function parseCell($index) { // If the cell is a date time - if($this->cellIsDate($index)) + if ($this->cellIsDate($index)) { // Parse the date return $this->parseDate(); } // Check if we want calculated values or not - elseif($this->reader->needsCalculation()) + elseif ($this->reader->needsCalculation()) { // Get calculated value return $this->getCalculatedValue(); @@ -447,6 +448,7 @@ protected function parseCell($index) protected function getCellValue() { $value = $this->cell->getValue(); + return $this->encode($value); } @@ -457,6 +459,7 @@ protected function getCellValue() protected function getCalculatedValue() { $value = $this->cell->getCalculatedValue(); + return $this->encode($value); } @@ -471,7 +474,7 @@ protected function encode($value) list($input, $output) = array_values(Config::get('excel::import.encoding', ['UTF-8', 'UTF-8'])); // If they are the same, return the value - if($input == $output) + if ($input == $output) return $value; // Encode @@ -485,7 +488,7 @@ protected function encode($value) protected function parseDate() { // If the date needs formatting - if($this->reader->needsDateFormatting()) + if ($this->reader->needsDateFormatting()) { // Parse the date with carbon return $this->parseDateAsCarbon(); @@ -504,7 +507,7 @@ protected function parseDate() protected function parseDateAsCarbon() { // If has a date - if($cellContent = $this->cell->getCalculatedValue()) + if ($cellContent = $this->cell->getCalculatedValue()) { // Convert excel time to php date object $date = PHPExcel_Shared_Date::ExcelToPHPObject($this->cell->getCalculatedValue())->format('Y-m-d H:i:s'); @@ -603,5 +606,4 @@ protected function reset() $this->indices = []; $this->isParsed = false; } - } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Parsers/ViewParser.php b/src/Maatwebsite/Excel/Parsers/ViewParser.php index 1819de23c..af7efb6df 100644 --- a/src/Maatwebsite/Excel/Parsers/ViewParser.php +++ b/src/Maatwebsite/Excel/Parsers/ViewParser.php @@ -26,18 +26,18 @@ class ViewParser { * Data array * @var array */ - public $data = array(); + public $data = []; /** * View merge data * @var array */ - public $mergeData = array(); + public $mergeData = []; /** * Construct the view parser * @param Html $reader - * @return void + * @return \Maatwebsite\Excel\Parsers\ViewParser */ public function __construct(Html $reader) { @@ -46,20 +46,21 @@ public function __construct(Html $reader) /** * Parse the view - * @param LaravelExcelWorksheet $sheet - * @return LaravelExcelWorksheet + * @param \Maatwebsite\Excel\Classes\LaravelExcelWorksheet $sheet + * @return \Maatwebsite\Excel\Classes\LaravelExcelWorksheet */ public function parse($sheet) { $html = View::make($this->getView(), $this->getData(), $this->getMergeData())->render(); + return $this->_loadHTML($sheet, $html); } /** * Load the HTML - * @param LaravelExcelWorksheet $sheet - * @param string $html - * @return LaravelExcelWorksheet + * @param \Maatwebsite\Excel\Classes\LaravelExcelWorksheet $sheet + * @param string $html + * @return \Maatwebsite\Excel\Classes\LaravelExcelWorksheet */ protected function _loadHTML($sheet, $html) { @@ -95,11 +96,11 @@ public function getMergeData() /** * Set the view - * @param string $view + * @param bool|string $view */ public function setView($view = false) { - if($view) + if ($view) $this->view = $view; } @@ -107,9 +108,9 @@ public function setView($view = false) * Set the data * @param array $data */ - public function setData($data = array()) + public function setData($data = []) { - if(!empty($data)) + if (!empty($data)) $this->data = array_merge($this->data, $data); } @@ -117,10 +118,9 @@ public function setData($data = array()) * Set the merge data * @param array $mergeData */ - public function setMergeData($mergeData = array()) + public function setMergeData($mergeData = []) { - if(!empty($mergeData)) + if (!empty($mergeData)) $this->mergeData = array_merge($this->mergeData, $mergeData); } - } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Readers/Batch.php b/src/Maatwebsite/Excel/Readers/Batch.php index 6af3c39de..749b14b61 100644 --- a/src/Maatwebsite/Excel/Readers/Batch.php +++ b/src/Maatwebsite/Excel/Readers/Batch.php @@ -27,22 +27,22 @@ class Batch { * Batch files * @var array */ - public $files = array(); + public $files = []; /** * Set allowed file extensions * @var array */ - protected $allowedFileExtensions = array( + protected $allowedFileExtensions = [ 'xls', 'xlsx', 'csv' - ); + ]; /** * Start the Batach * @param Excel $excel - * @param array $files + * @param array $files * @param Closure $callback * @return Excel */ @@ -51,13 +51,13 @@ public function start(Excel $excel, $files, Closure $callback) // Set excel object $this->excel = $excel; - // Set files + // Set files $this->_setFiles($files); // Do the callback - if($callback instanceof Closure) + if ($callback instanceof Closure) { - foreach($this->getFiles() as $file) + foreach ($this->getFiles() as $file) { // Load the file $excel = $this->excel->load($file); @@ -89,34 +89,37 @@ public function getFiles() protected function _setFiles($files) { // If the param is an array, these will be the files for the batch import - if(is_array($files)) + if (is_array($files)) { $this->files = $this->_getFilesByArray($files); } // Get all the files inside a folder - elseif(is_string($files)) + elseif (is_string($files)) { $this->files = $this->_getFilesByFolder($files); } // Check if files were found - if(empty($this->files)) + if (empty($this->files)) throw new LaravelExcelException('[ERROR]: No files were found. Batch terminated.'); } /** * Set files by array * @param array $array - * @return void + * @return array */ protected function _getFilesByArray($array) { + $files = []; // Make sure we have real paths - foreach($array as $i => $file) + foreach ($array as $i => $file) { - $this->files[$i] = realpath($file) ? $file : base_path($file); + $files[$i] = realpath($file) ? $file : base_path($file); } + + return $files; } /** @@ -127,17 +130,18 @@ protected function _getFilesByArray($array) protected function _getFilesByFolder($folder) { // Check if it's a real path - if(!realpath($folder)) + if (!realpath($folder)) $folder = base_path($folder); // Find path names matching our pattern of excel extensions - $glob = glob($folder.'/*.{'. implode(',', $this->allowedFileExtensions) .'}', GLOB_BRACE); + $glob = glob($folder . '/*.{' . implode(',', $this->allowedFileExtensions) . '}', GLOB_BRACE); // If no matches, return empty array - if ($glob === false) return array(); + if ($glob === false) return []; // Return files - return array_filter($glob, function($file) { + return array_filter($glob, function ($file) + { return filetype($file) == 'file'; }); } diff --git a/src/Maatwebsite/Excel/Readers/ConfigReader.php b/src/Maatwebsite/Excel/Readers/ConfigReader.php index be1812e9b..5a9b3ff2b 100644 --- a/src/Maatwebsite/Excel/Readers/ConfigReader.php +++ b/src/Maatwebsite/Excel/Readers/ConfigReader.php @@ -48,7 +48,7 @@ class ConfigReader { * Constructor * @param PHPExcel $excel * @param string $config - * @param callback $callback + * @param callback $callback */ public function __construct(PHPExcel $excel, $config = 'excel::import', $callback = null) { @@ -64,7 +64,8 @@ public function __construct(PHPExcel $excel, $config = 'excel::import', $callbac /** * Start the import - * @param callback $callback + * @param bool|callable $callback $callback + * @throws \PHPExcel_Exception * @return void */ public function start($callback = false) @@ -73,10 +74,10 @@ public function start($callback = false) $this->sheetCollection = new SheetCollection(); // Get the sheet names - if($sheets = $this->excel->getSheetNames()) + if ($sheets = $this->excel->getSheetNames()) { // Loop through the sheets - foreach($sheets as $index => $name) + foreach ($sheets as $index => $name) { // Set sheet name $this->sheetName = $name; @@ -85,7 +86,7 @@ public function start($callback = false) $this->sheet = $this->excel->setActiveSheetIndex($index); // Do the callback - if($callback instanceof Closure) + if ($callback instanceof Closure) { call_user_func($callback, $this); } @@ -118,7 +119,7 @@ protected function valueByIndex($field) $field = snake_case($field); // Get coordinate - if($coordinate = $this->getCoordinateByKey($field)) + if ($coordinate = $this->getCoordinateByKey($field)) { // return cell value by coordinate return $this->getCellValueByCoordinate($coordinate); @@ -134,12 +135,13 @@ protected function valueByIndex($field) */ protected function getCellValueByCoordinate($coordinate) { - if($this->sheet) + if ($this->sheet) { - if(str_contains($coordinate, ':')) + if (str_contains($coordinate, ':')) { // We want to get a range of cells $values = $this->sheet->rangeToArray($coordinate); + return $values; } else diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 1d95dabee..f27678100 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -70,11 +70,11 @@ class Html extends PHPExcel_Reader_HTML { /** * Loads PHPExcel from file * - * @param string $pFilename - * @param boolean $isString - * @param PHPExcel|LaravelExcelWorksheet|null $obj + * @param string $pFilename + * @param boolean $isString + * @param bool|LaravelExcelWorksheet|null|PHPExcel $obj + * @throws \PHPExcel_Reader_Exception * @return LaravelExcelWorksheet - * @throws PHPExcel_Reader_Exception */ public function load($pFilename, $isString = false, $obj = false) { @@ -239,7 +239,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & $attributeArray = []; // If it's a column, and it's row has a class, style it - if(in_array($row, array_keys($this->styleForRows))) + if (in_array($row, array_keys($this->styleForRows))) $this->styleByClass($sheet, $column, $row, $this->styleForRows[$row]); // Loop through the child's attributes @@ -290,7 +290,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & case 'class': // If it's a tr, remember the row number - if($child->nodeName == 'tr') + if ($child->nodeName == 'tr') $this->styleForRows[$row] = $attribute->value; $this->styleByClass($sheet, $column, $row, $attribute->value); @@ -690,6 +690,8 @@ private function _flushCell($sheet, &$column, $row, &$cellContent) * @param LaravelExcelWorksheet $sheet * @param string $row * @param integer $column + * @param $cellContent + * @throws \PHPExcel_Exception * @return LaravelExcelWorksheet */ protected function _processHeadings($child, $sheet, $row, $column, $cellContent) @@ -1203,10 +1205,10 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) // wrap-text case 'wrap-text': - if($value == 'true') + if ($value == 'true') $wrap = true; - if(!$value || $value == 'false') + if (!$value || $value == 'false') $wrap = false; $cells->getAlignment()->setWrapText($wrap); @@ -1270,6 +1272,8 @@ public function borderStyle($style) * @param $sheet * @param $column * @param $row + * @param $cellContent + * @throws \PHPExcel_Exception * @return array */ private function processMergedCells($sheet, &$column, $row, $cellContent) @@ -1295,7 +1299,7 @@ private function processMergedCells($sheet, &$column, $row, $cellContent) $column = $newCol; // If it's a column, and it's row has a class, style it - if(in_array($row, array_keys($this->styleForRows))) + if (in_array($row, array_keys($this->styleForRows))) $this->styleByClass($sheet, $column, $row, $this->styleForRows[$row]); $this->_flushCell($sheet, $newCol, $row, $cellContent); diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index 3214b3a27..b85bae0ee 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -23,7 +23,7 @@ class LaravelExcelReader { /** * Excel object - * @var PHPExcel + * @var \PHPExcel */ public $excel; @@ -43,7 +43,7 @@ class LaravelExcelReader { * Selected columns * @var array */ - public $columns = array(); + public $columns = []; /** * Spreadsheet title @@ -105,7 +105,7 @@ class LaravelExcelReader { */ public $separator = false; - /** + /** * Ignore empty cells * @var boolean */ @@ -121,7 +121,7 @@ class LaravelExcelReader { * The date columns * @var array */ - public $dateColumns = array(); + public $dateColumns = []; /** * If the file has a heading or not @@ -151,18 +151,19 @@ class LaravelExcelReader { * Selected sheets * @var array */ - public $selectedSheets = array(); + public $selectedSheets = []; /** * Selected sheet indices * @var array */ - public $selectedSheetIndices = array(); + public $selectedSheetIndices = []; /** * Construct new reader - * @param FileSystem $files + * @param Filesystem $filesystem * @param FormatIdentifier $identifier + * @internal param Filesystem $files */ public function __construct(Filesystem $filesystem, FormatIdentifier $identifier) { @@ -172,8 +173,8 @@ public function __construct(Filesystem $filesystem, FormatIdentifier $identifier /** * Load a file - * @param string $file - * @param boolean $firstRowAsIndex + * @param string $file + * @param bool $encoding * @return LaravelExcelReader */ public function load($file, $encoding = false) @@ -182,7 +183,7 @@ public function load($file, $encoding = false) $this->_init($file, $encoding); // Only fetch selected sheets if necessary - if($this->sheetsSelected()) + if ($this->sheetsSelected()) $this->reader->setLoadSheetsOnly($this->selectedSheets); // Load the file @@ -212,29 +213,32 @@ public function sheetsSelected() /** * Check if the file was selected by index - * @param [type] $index [description] - * @return boolean [description] + * @param $index + * @return boolean */ public function isSelectedByIndex($index) { $selectedSheets = $this->getSelectedSheetIndices(); - if(empty($selectedSheets)) return true; + if (empty($selectedSheets)) return true; + return in_array($index, $selectedSheets) ? true : false; } /** * Set the selected sheet indices - * @param [type] $sheets [description] + * @param $sheets + * @return $this */ public function setSelectedSheetIndices($sheets) { $this->selectedSheetIndices = $sheets; + return $this; } /** * Return the selected sheets - * @return [type] [description] + * @return array */ public function getSelectedSheetIndices() { @@ -250,18 +254,20 @@ public function remember($minutes) { $this->remembered = true; $this->cacheMinutes = $minutes; + return $this; } /** * Read the file through a config file - * @param stirng $config + * @param string $config * @param callback|null $callback * @return SheetCollection */ public function byConfig($config, $callback = null) { $config = new ConfigReader($this->excel, $config, $callback); + return $config->getSheetCollection(); } @@ -274,6 +280,7 @@ public function take($amount) { // Set limit $this->limit = $amount; + return $this; } @@ -286,6 +293,7 @@ public function skip($amount) { // Set skip amount $this->skip = $amount; + return $this; } @@ -308,12 +316,13 @@ public function limit($take, $skip = 0) /** * Select certain columns - * @param array $columns + * @param array $columns * @return LaravelExcelReader */ - public function select($columns = array()) + public function select($columns = []) { $this->columns = array_merge($this->columns, $columns); + return $this; } @@ -322,7 +331,7 @@ public function select($columns = array()) * @param array $columns * @return LaravelExcelReader */ - public function all($columns = array()) + public function all($columns = []) { return $this->get($columns); } @@ -332,7 +341,7 @@ public function all($columns = array()) * @param array $columns * @return SheetCollection|RowCollection */ - public function first($columns = array()) + public function first($columns = []) { return $this->take(1)->get($columns)->first(); } @@ -342,13 +351,15 @@ public function first($columns = array()) * @param array $columns * @return SheetCollection|RowCollection */ - public function get($columns = array()) + public function get($columns = []) { - if($this->remembered) + if ($this->remembered) { // Return cached results - return Cache::remember(md5($this->file), $this->cacheMinutes, function() use (&$columns) { + return Cache::remember(md5($this->file), $this->cacheMinutes, function () use (&$columns) + { $this->_parseFile($columns); + return $this->parsed; }); } @@ -356,6 +367,7 @@ public function get($columns = array()) { // return parsed file $this->_parseFile($columns); + return $this->parsed; } } @@ -372,10 +384,10 @@ public function each($callback) /** * Parse the file to an array. - * @param array $columns - * @return array + * @param array $columns + * @return array */ - public function toArray($columns = array()) + public function toArray($columns = []) { return (array) $this->get($columns)->toArray(); } @@ -385,28 +397,30 @@ public function toArray($columns = array()) * @param array $columns * @return SheetCollection|RowCollection */ - public function toObject($columns = array()) + public function toObject($columns = []) { return $this->get($columns); } /** * Dump the parsed file to a readable array - * @param array $columns - * @param boolean $die + * @param array $columns + * @param boolean $die + * @return string */ - public function dump($columns = array(), $die = false) + public function dump($columns = [], $die = false) { echo '
';
-            $die ? dd($this->get($columns)) : var_dump($this->get($columns));
+        $die ? dd($this->get($columns)) : var_dump($this->get($columns));
         echo '
'; } /** * Die and dump * @param array $columns + * @return string */ - public function dd($columns = array()) + public function dd($columns = []) { return $this->dump($columns, true); } @@ -414,18 +428,18 @@ public function dd($columns = array()) /** * Init the loading * @param string $file - * @param string|boolean $firstRowAsIndex + * @param bool $encoding * @return void */ protected function _init($file, $encoding = false) { // Set the extension $this->_setFile($file) - ->setExtension() - ->setTitle() - ->_setFormat() - ->_setReader() - ->_setInputEncoding($encoding); + ->setExtension() + ->setTitle() + ->_setFormat() + ->_setReader() + ->_setInputEncoding($encoding); } /** @@ -447,10 +461,11 @@ public function injectExcel($excel) protected function _setFile($file) { // check if we have a correct path - if(!realpath($file)) + if (!realpath($file)) $file = base_path($file); $this->file = $file; + return $this; } @@ -462,6 +477,7 @@ protected function _setFile($file) public function setTitle($title = false) { $this->title = $title ? $title : basename($this->file, '.' . $this->ext); + return $this; } @@ -472,19 +488,21 @@ public function setTitle($title = false) */ public function setExtension($ext = false) { - $this->ext = $ext ? $ext: $this->filesystem->extension($this->file); + $this->ext = $ext ? $ext : $this->filesystem->extension($this->file); + return $this; } /** * Set the date format - * @param string $format The date format + * @param bool|string $format The date format * @return LaraveExcelReader */ public function setDateFormat($format = false) { $this->formatDates = $format ? true : false; $this->dateFormat = $format; + return $this; } @@ -498,6 +516,7 @@ public function formatDates($boolean = true, $format = false) { $this->formatDates = $boolean; $this->setDateFormat($format); + return $this; } @@ -510,6 +529,7 @@ public function setDateColumns() $this->formatDates = true; $columns = func_get_args(); $this->dateColumns = array_merge($this->dateColumns, array_flatten($columns)); + return $this; } @@ -521,6 +541,7 @@ public function setDateColumns() public function noHeading($boolean = true) { $this->noHeading = $boolean; + return $this; } @@ -532,12 +553,14 @@ public function noHeading($boolean = true) public function setSeparator($separator) { $this->separator = $separator; + return $this; } /** * Spelling mistake backwards compatibility - * @param [type] $separator [description] + * @param $separator + * @return \Maatwebsite\Excel\Readers\LaraveExcelReader */ public function setSeperator($separator) { @@ -553,17 +576,19 @@ public function setSeperator($separator) public function setDelimiter($delimiter) { $this->reader->setDelimiter($delimiter); + return $this; } /** * Set default calculate - * @param bool $boolean Calculate yes or no - * @return LaraveExcelReader + * @param bool $boolean Calculate yes or no + * @return LaraveExcelReader */ public function calculate($boolean = true) { $this->calculate = $boolean; + return $this; } @@ -575,6 +600,7 @@ public function calculate($boolean = true) public function ignoreEmpty($boolean = true) { $this->ignoreEmpty = $boolean; + return $this; } @@ -584,9 +610,10 @@ public function ignoreEmpty($boolean = true) */ public function hasHeading() { - if(!$this->noHeading) + if (!$this->noHeading) { $config = Config::get('excel::import.heading', true); + return $config !== false && $config !== 'numeric'; } @@ -599,7 +626,7 @@ public function hasHeading() */ public function getSeparator() { - if($this->separator) + if ($this->separator) return $this->separator; return Config::get('excel::import.separator', Config::get('excel::import.seperator', '_')); @@ -675,6 +702,7 @@ public function getLimit() protected function _setFormat() { $this->format = $this->identifier->getFormatByFile($this->file); + return $this; } @@ -683,7 +711,7 @@ protected function _setFormat() * @param array $columns * @return void */ - protected function _parseFile($columns = array()) + protected function _parseFile($columns = []) { // Merge the selected columns $columns = array_merge($this->columns, $columns); @@ -702,6 +730,7 @@ protected function _setReader() // Init the reader $this->reader = PHPExcel_IOFactory::createReader($this->format); $this->_setReaderDefaults(); + return $this; } @@ -712,7 +741,7 @@ protected function _setReader() */ protected function _setInputEncoding($encoding = false) { - if($this->format == 'CSV') + if ($this->format == 'CSV') { // If no encoding was given, use the config value $encoding = $encoding ? $encoding : Config::get('excel::import.encoding.input', 'UTF-8'); @@ -729,7 +758,7 @@ protected function _setInputEncoding($encoding = false) protected function _setReaderDefaults() { // Set CSV delimiter - if($this->format == 'CSV') + if ($this->format == 'CSV') { $this->reader->setDelimiter(Config::get('excel::csv.delimiter', ',')); $this->reader->setEnclosure(Config::get('excel::csv.enclosure', '"')); @@ -749,7 +778,7 @@ protected function _setReaderDefaults() $this->formatDates = Config::get('excel::import.dates.enabled', true); // Set default date columns - $this->dateColumns = Config::get('excel::import.dates.columns', array()); + $this->dateColumns = Config::get('excel::import.dates.columns', []); } /** @@ -773,27 +802,25 @@ public function getExcel() /** * Dynamically call methods * @param string $method - * @param array $params + * @param array $params * @throws LaravelExcelException */ public function __call($method, $params) { // Call a php excel method - if(method_exists($this->excel, $method)) + if (method_exists($this->excel, $method)) { // Call the method from the excel object with the given params - return call_user_func_array(array($this->excel, $method), $params); + return call_user_func_array([$this->excel, $method], $params); } // If it's a reader method - elseif(method_exists($this->reader, $method)) + elseif (method_exists($this->reader, $method)) { // Call the method from the excel object with the given params - return call_user_func_array(array($this->reader, $method), $params); + return call_user_func_array([$this->reader, $method], $params); } - throw new LaravelExcelException('[ERROR] Reader method ['. $method .'] does not exist.'); - + throw new LaravelExcelException('[ERROR] Reader method [' . $method . '] does not exist.'); } - } \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Writers/CellWriter.php b/src/Maatwebsite/Excel/Writers/CellWriter.php index 646b960a3..6ea5851e6 100644 --- a/src/Maatwebsite/Excel/Writers/CellWriter.php +++ b/src/Maatwebsite/Excel/Writers/CellWriter.php @@ -46,7 +46,7 @@ public function __construct($cells, LaravelExcelWorksheet $sheet) public function setValue($value) { // Only set cell value for single cells - if(!str_contains($this->cells, ':')) + if (!str_contains($this->cells, ':')) { $this->sheet->setCellValue($this->cells, $value); } @@ -79,7 +79,7 @@ public function setFontColor($color, $colorType = 'rgb') /** * Set the font - * @param array $right + * @param $styles * @return CellWriter */ public function setFont($styles) @@ -94,9 +94,9 @@ public function setFont($styles) */ public function setFontFamily($family) { - return $this->setStyle('font', array( - 'name' => $family - )); + return $this->setStyle('font', [ + 'name' => $family + ]); } /** @@ -106,9 +106,9 @@ public function setFontFamily($family) */ public function setFontSize($size) { - return $this->setStyle('font', array( - 'size' => $size - )); + return $this->setStyle('font', [ + 'size' => $size + ]); } /** @@ -118,36 +118,36 @@ public function setFontSize($size) */ public function setFontWeight($bold = true) { - return $this->setStyle('font', array( - 'bold' => ($bold == 'bold' || $bold) ? true : false - )); + return $this->setStyle('font', [ + 'bold' => ($bold == 'bold' || $bold) ? true : false + ]); } /** * Set border - * @param string $top - * @param boolean $right - * @param boolean $bottom - * @param boolean $left + * @param string $top + * @param bool|string $right + * @param bool|string $bottom + * @param bool|string $left * @return CellWriter */ public function setBorder($top = 'none', $right = 'none', $bottom = 'none', $left = 'none') { // Set the border styles - $styles = is_array($top) ? $top : array( - 'top' => array( + $styles = is_array($top) ? $top : [ + 'top' => [ 'style' => $top - ), - 'left' => array( + ], + 'left' => [ 'style' => $left, - ), - 'right' => array( + ], + 'right' => [ 'style' => $right, - ), - 'bottom' => array( + ], + 'bottom' => [ 'style' => $bottom, - ) - ); + ] + ]; return $this->setStyle('borders', $styles); } @@ -159,9 +159,9 @@ public function setBorder($top = 'none', $right = 'none', $bottom = 'none', $lef */ public function setAlignment($alignment) { - return $this->setStyle('alignment', array( - 'horizontal' => $alignment - )); + return $this->setStyle('alignment', [ + 'horizontal' => $alignment + ]); } /** @@ -171,14 +171,14 @@ public function setAlignment($alignment) */ public function setValignment($alignment) { - return $this->setStyle('alignment', array( - 'vertical' => $alignment - )); + return $this->setStyle('alignment', [ + 'vertical' => $alignment + ]); } /** * Set the color style - * @param string $style + * @param $styleType * @param string $color * @param boolean $type * @param string $colorType @@ -187,18 +187,18 @@ public function setValignment($alignment) protected function setColorStyle($styleType, $color, $type = false, $colorType = 'rgb') { // Set the styles - $styles = is_array($color) ? $color : array( - 'type' => $type, - 'color' => array($colorType => str_replace('#', '', $color)) - ); + $styles = is_array($color) ? $color : [ + 'type' => $type, + 'color' => [$colorType => str_replace('#', '', $color)] + ]; return $this->setStyle($styleType, $styles); } /** * Set style + * @param $styleType * @param string $styles - * @param array $styles * @return CellWriter */ protected function setStyle($styleType, $styles) @@ -207,20 +207,19 @@ protected function setStyle($styleType, $styles) $style = $this->getCellStyle(); // Apply style from array - $style->applyFromArray(array( + $style->applyFromArray([ $styleType => $styles - )); + ]); return $this; } /** * Get the cell style - * @return PHPExcel_Style + * @return \PHPExcel_Style */ protected function getCellStyle() { return $this->sheet->getStyle($this->cells); } - } diff --git a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php index 5bf3f5b24..493b514ca 100644 --- a/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php +++ b/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php @@ -25,19 +25,19 @@ class LaravelExcelWriter { /** * Spreadsheet filename - * @var stirng + * @var string */ public $filename; /** * Spreadsheet title - * @var stirng + * @var string */ public $title; /** * Excel object - * @var PHPExcel + * @var \PHPExcel */ public $excel; @@ -105,13 +105,14 @@ public function __construct(Response $response, FileSystem $filesystem, FormatId /** * Inject the excel object * @param PHPExcel $excel + * @param bool $reset * @return void */ public function injectExcel($excel, $reset = true) { $this->excel = $excel; - if($reset) + if ($reset) $this->_reset(); } @@ -124,16 +125,19 @@ public function setTitle($title) { $this->title = $title; $this->getProperties()->setTitle($title); + return $this; } /** * Set the filename - * @param [type] $name [description] + * @param $name + * @return $this */ public function setFileName($name) { $this->filename = $name; + return $this; } @@ -162,7 +166,7 @@ public function getFileName() * @param array $mergeData * @return LaravelExcelWriter */ - public function shareView($view, $data = array(), $mergeData = array()) + public function shareView($view, $data = [], $mergeData = []) { // Get the parser $this->getParser(); @@ -181,7 +185,7 @@ public function shareView($view, $data = array(), $mergeData = array()) */ public function setView() { - return call_user_func_array(array($this, 'shareView'), func_get_args()); + return call_user_func_array([$this, 'shareView'], func_get_args()); } /** @@ -190,12 +194,12 @@ public function setView() */ public function loadView() { - return call_user_func_array(array($this, 'shareView'), func_get_args()); + return call_user_func_array([$this, 'shareView'], func_get_args()); } /** * Create a new sheet - * @param string $title + * @param string $title * @param callback|null $callback * @return LaravelExcelWriter */ @@ -205,7 +209,7 @@ public function sheet($title, $callback = null) $this->sheet = $this->excel->createSheet(null, $title); // If a parser was set, inject it - if($this->parser) + if ($this->parser) $this->sheet->setParser($this->parser); // Set the sheet title @@ -215,11 +219,11 @@ public function sheet($title, $callback = null) $this->sheet->setDefaultPageSetup(); // Do the callback - if($callback instanceof Closure) + if ($callback instanceof Closure) call_user_func($callback, $this->sheet); // Autosize columns when no user didn't change anything about column sizing - if(!$this->sheet->hasFixedSizeColumns()) + if (!$this->sheet->hasFixedSizeColumns()) $this->sheet->setAutosize(Config::get('excel::export.autosize', false)); // Parse the sheet @@ -230,13 +234,14 @@ public function sheet($title, $callback = null) /** * Set data for the current sheet - * @param array $array + * @param array $array * @return LaravelExcelWriter */ public function with(Array $array) { // Add the vars $this->fromArray($array); + return $this; } @@ -269,24 +274,25 @@ public function download($ext = 'xls') /** * Download a file + * @throws LaravelExcelException * @return void */ protected function _download() { // Set the headers - $this->_setHeaders(array( + $this->_setHeaders([ - 'Content-Type' => $this->contentType, - 'Content-Disposition' => 'attachment; filename="' . $this->filename . '.' . $this->ext . '"', - 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past - 'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'), - 'Cache-Control' => 'cache, must-revalidate', - 'Pragma' => 'public' + 'Content-Type' => $this->contentType, + 'Content-Disposition' => 'attachment; filename="' . $this->filename . '.' . $this->ext . '"', + 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past + 'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'), + 'Cache-Control' => 'cache, must-revalidate', + 'Pragma' => 'public' - )); + ]); // Check if writer isset - if(!$this->writer) + if (!$this->writer) throw new LaravelExcelException('[ERROR] No writer was set.'); // Download @@ -321,17 +327,16 @@ public function store($ext = 'xls', $path = false, $returnInfo = false) $this->writer->save($toStore); // Return file info - if($this->returnInfo($returnInfo)) + if ($this->returnInfo($returnInfo)) { // Send back information about the stored file - return array( + return [ 'full' => $toStore, 'path' => $this->storagePath, 'file' => $this->filename . '.' . $this->ext, 'title' => $this->filename, 'ext' => $this->ext - ); - + ]; } // Return itself @@ -350,9 +355,10 @@ public function returnInfo($returnInfo = false) /** * Store the excel file to the server - * @param str $ext The file extension - * @param str $path The save path - * @return LaravelExcelWriter + * @param str|string $ext The file extension + * @param bool|str $path The save path + * @param bool $returnInfo + * @return LaravelExcelWriter */ public function save($ext = 'xls', $path = false, $returnInfo = false) { @@ -361,12 +367,13 @@ public function save($ext = 'xls', $path = false, $returnInfo = false) /** * Start render of a new spreadsheet + * @throws LaravelExcelException * @return void */ protected function _render() { // There should be enough sheets to continue rendering - if($this->excel->getSheetCount() < 0) + if ($this->excel->getSheetCount() < 0) throw new LaravelExcelException('[ERROR] Aborting spreadsheet render: no sheets were created.'); // Set the format @@ -395,7 +402,7 @@ public function getExcel() public function getParser() { // Init the parser - if(!$this->parser) + if (!$this->parser) $this->parser = app('excel.parsers.view'); return $this->parser; @@ -413,7 +420,7 @@ public function getSheet() /** * Set attributes * @param string $setter - * @param array $params + * @param array $params */ protected function _setAttribute($setter, $params) { @@ -421,10 +428,10 @@ protected function _setAttribute($setter, $params) $key = lcfirst(str_replace('set', '', $setter)); // If is an allowed property - if($this->excel->isChangeableProperty($setter)) + if ($this->excel->isChangeableProperty($setter)) { // Set the properties - call_user_func_array(array($this->excel->getProperties(), $setter), $params); + call_user_func_array([$this->excel->getProperties(), $setter], $params); } } @@ -435,7 +442,7 @@ protected function _setAttribute($setter, $params) protected function _setFormat() { // Get extension - $this->ext = strtolower($this->ext); + $this->ext = strtolower($this->ext); // get the file format $this->format = $this->identifier->getFormatByExtension($this->ext); @@ -453,7 +460,7 @@ protected function _setWriter() $this->writer = PHPExcel_IOFactory::createWriter($this->excel, $this->format); // Set CSV delimiter - if($this->format == 'CSV') + if ($this->format == 'CSV') { $this->writer->setDelimiter(Config::get('excel::csv.delimiter', ',')); $this->writer->setEnclosure(Config::get('excel::csv.enclosure', '"')); @@ -468,12 +475,14 @@ protected function _setWriter() /** * Set the headers + * @param $headers + * @throws LaravelExcelException */ protected function _setHeaders($headers) { - if ( headers_sent() ) throw new LaravelExcelException('[ERROR]: Headers already sent'); + if (headers_sent()) throw new LaravelExcelException('[ERROR]: Headers already sent'); - foreach($headers as $header => $value) + foreach ($headers as $header => $value) { header($header . ': ' . $value); } @@ -481,6 +490,7 @@ protected function _setHeaders($headers) /** * Set the storage path + * @param bool $path * @return void */ protected function _setStoragePath($path = false) @@ -492,7 +502,7 @@ protected function _setStoragePath($path = false) $this->storagePath = rtrim($path, '/'); // Make sure the storage path exists - if(!$this->filesystem->isWritable($this->storagePath)) + if (!$this->filesystem->isWritable($this->storagePath)) $this->filesystem->makeDirectory($this->storagePath, 0777, true); } @@ -508,34 +518,38 @@ protected function _reset() /** * Dynamically call methods * @param string $method - * @param array $params + * @param array $params + * @throws LaravelExcelException * @return LaravelExcelWriter */ public function __call($method, $params) { // If the dynamic call starts with "set" - if(starts_with($method, 'set') && $this->excel->isChangeableProperty($method)) + if (starts_with($method, 'set') && $this->excel->isChangeableProperty($method)) { $this->_setAttribute($method, $params); + return $this; } // Call a php excel method - elseif(method_exists($this->excel, $method)) + elseif (method_exists($this->excel, $method)) { // Call the method from the excel object with the given params - $return = call_user_func_array(array($this->excel, $method), $params); + $return = call_user_func_array([$this->excel, $method], $params); + return $return ? $return : $this; } // Call a php excel sheet method - elseif(method_exists($this->excel->getActiveSheet(), $method)) + elseif (method_exists($this->excel->getActiveSheet(), $method)) { // Call the method from the excel object with the given params - $return = call_user_func_array(array($this->excel->getActiveSheet(), $method), $params); + $return = call_user_func_array([$this->excel->getActiveSheet(), $method], $params); + return $return ? $return : $this; } - throw new LaravelExcelException('[ERROR] Writer method ['. $method .'] does not exist.'); + throw new LaravelExcelException('[ERROR] Writer method [' . $method . '] does not exist.'); } } \ No newline at end of file diff --git a/src/config/cache.php b/src/config/cache.php index 178cdddd8..5a1d085e8 100644 --- a/src/config/cache.php +++ b/src/config/cache.php @@ -1,13 +1,13 @@ true, + 'enable' => true, /* |-------------------------------------------------------------------------- @@ -20,31 +20,31 @@ | memory|gzip|serialized|igbinary|discISAM|apc|memcache|temp|wincache|sqlite|sqlite3 | */ - 'driver' => 'memory', + 'driver' => 'memory', /* |-------------------------------------------------------------------------- | Cache settings |-------------------------------------------------------------------------- */ - 'settings' => array( + 'settings' => [ - 'memoryCacheSize' => '32MB', - 'cacheTime' => 600 + 'memoryCacheSize' => '32MB', + 'cacheTime' => 600 - ), + ], /* |-------------------------------------------------------------------------- | Memcache settings |-------------------------------------------------------------------------- */ - 'memcache' => array( + 'memcache' => [ - 'host' => 'localhost', - 'port' => 11211, + 'host' => 'localhost', + 'port' => 11211, - ), + ], /* |-------------------------------------------------------------------------- @@ -52,6 +52,6 @@ |-------------------------------------------------------------------------- */ - 'dir' => storage_path('cache') + 'dir' => storage_path('cache') -); \ No newline at end of file +]; \ No newline at end of file diff --git a/src/config/config.php b/src/config/config.php index 727d300fd..872d49555 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -6,15 +6,15 @@ * * Licensed under the LPGL. * - * @package Laravel-4 PHPExcel - * @version 1.* - * @author Maatwebsite - * @license LGPL + * @package Laravel-4 PHPExcel + * @version 1.* + * @author Maatwebsite + * @license LGPL * @copyright (c) 2013, Maatwebsite - * @link http://maatwebsite.nl + * @link http://maatwebsite.nl */ -return array( +return [ /* |-------------------------------------------------------------------------- @@ -24,45 +24,45 @@ | The default properties when creating a new Excel file | */ - 'properties' => array( - 'creator' => 'Maatwebsite', - 'lastModifiedBy' => 'Maatwebsite', - 'title' => 'Spreadsheet', - 'description' => 'Default spreadsheet export', - 'subject' => 'Spreadsheet export', - 'keywords' => 'maatwebsite, excel, export', - 'category' => 'Excel', - 'manager' => 'Maatwebsite', - 'company' => 'Maatwebsite', - ), + 'properties' => [ + 'creator' => 'Maatwebsite', + 'lastModifiedBy' => 'Maatwebsite', + 'title' => 'Spreadsheet', + 'description' => 'Default spreadsheet export', + 'subject' => 'Spreadsheet export', + 'keywords' => 'maatwebsite, excel, export', + 'category' => 'Excel', + 'manager' => 'Maatwebsite', + 'company' => 'Maatwebsite', + ], /* |-------------------------------------------------------------------------- | Sheets settings |-------------------------------------------------------------------------- */ - 'sheets' => array( + 'sheets' => [ /* |-------------------------------------------------------------------------- | Default page setup |-------------------------------------------------------------------------- */ - 'pageSetup' => array( - 'orientation' => 'portrait', - 'paperSize' => '9', - 'scale' => '100', - 'fitToPage' => false, - 'fitToHeight' => true, - 'fitToWidth' => true, - 'columnsToRepeatAtLeft' => array('', ''), - 'rowsToRepeatAtTop' => array(0, 0), - 'horizontalCentered' => false, - 'verticalCentered' => false, - 'printArea' => null, - 'firstPageNumber' => null, - ), - ), + 'pageSetup' => [ + 'orientation' => 'portrait', + 'paperSize' => '9', + 'scale' => '100', + 'fitToPage' => false, + 'fitToHeight' => true, + 'fitToWidth' => true, + 'columnsToRepeatAtLeft' => ['', ''], + 'rowsToRepeatAtTop' => [0, 0], + 'horizontalCentered' => false, + 'verticalCentered' => false, + 'printArea' => null, + 'firstPageNumber' => null, + ], + ], /* |-------------------------------------------------------------------------- @@ -73,6 +73,6 @@ | */ - 'creator' => 'Maatwebsite', + 'creator' => 'Maatwebsite', -); +]; diff --git a/src/config/csv.php b/src/config/csv.php index a80a80982..88393bd6b 100644 --- a/src/config/csv.php +++ b/src/config/csv.php @@ -1,6 +1,6 @@ ',', + 'delimiter' => ',', /* |-------------------------------------------------------------------------- @@ -19,7 +19,7 @@ |-------------------------------------------------------------------------- */ - 'enclosure' => '"', + 'enclosure' => '"', /* |-------------------------------------------------------------------------- @@ -28,4 +28,4 @@ */ 'line_ending' => "\r\n" -); \ No newline at end of file +]; \ No newline at end of file diff --git a/src/config/export.php b/src/config/export.php index 9ca8e1206..d9f02f607 100644 --- a/src/config/export.php +++ b/src/config/export.php @@ -1,6 +1,6 @@ true, + 'autosize' => true, /* |-------------------------------------------------------------------------- @@ -34,7 +34,7 @@ | having the appropriate fonts installed. | */ - 'autosize-method' => PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX, + 'autosize-method' => PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX, /* |-------------------------------------------------------------------------- @@ -45,7 +45,7 @@ | will automatically be used as first row (table heading) | */ - 'generate_heading_by_indices' => true, + 'generate_heading_by_indices' => true, /* |-------------------------------------------------------------------------- @@ -66,7 +66,7 @@ | Default sheet settings |-------------------------------------------------------------------------- */ - 'sheets' => array( + 'sheets' => [ /* |-------------------------------------------------------------------------- @@ -80,29 +80,29 @@ | Default order: array(top, right, bottom, left) | */ - 'page_margin' => false, + 'page_margin' => false, /* |-------------------------------------------------------------------------- | Value in source array that stands for blank cell |-------------------------------------------------------------------------- */ - 'nullValue' => null, + 'nullValue' => null, /* |-------------------------------------------------------------------------- | Insert array starting from this cell address as the top left coordinate |-------------------------------------------------------------------------- */ - 'startCell' => 'A1', + 'startCell' => 'A1', /* |-------------------------------------------------------------------------- | Apply strict comparison when testing for null values in the array |-------------------------------------------------------------------------- */ - 'strictNullComparison' => false - ), + 'strictNullComparison' => false + ], /* |-------------------------------------------------------------------------- @@ -110,7 +110,7 @@ |-------------------------------------------------------------------------- */ - 'store' => array( + 'store' => [ /* |-------------------------------------------------------------------------- @@ -120,7 +120,7 @@ | The path we want to save excel file to | */ - 'path' => storage_path('exports'), + 'path' => storage_path('exports'), /* |-------------------------------------------------------------------------- @@ -130,7 +130,7 @@ | Whether we want to return information about the stored file or not | */ - 'returnInfo' => false + 'returnInfo' => false - ) -); + ] +]; diff --git a/src/config/import.php b/src/config/import.php index c7be66db0..253e615c1 100644 --- a/src/config/import.php +++ b/src/config/import.php @@ -1,6 +1,6 @@ 'slugged', + 'heading' => 'slugged', /* |-------------------------------------------------------------------------- @@ -25,7 +25,7 @@ | */ - 'separator' => '_', + 'separator' => '_', /* |-------------------------------------------------------------------------- @@ -37,7 +37,7 @@ | */ - 'to_ascii' => true, + 'to_ascii' => true, /* |-------------------------------------------------------------------------- @@ -45,12 +45,12 @@ |-------------------------------------------------------------------------- */ - 'encoding' => array( + 'encoding' => [ - 'input' => 'UTF-8', - 'output' => 'UTF-8' + 'input' => 'UTF-8', + 'output' => 'UTF-8' - ), + ], /* |-------------------------------------------------------------------------- @@ -61,7 +61,7 @@ | */ - 'calculate' => true, + 'calculate' => true, /* |-------------------------------------------------------------------------- @@ -72,7 +72,7 @@ | */ - 'ignoreEmpty' => false, + 'ignoreEmpty' => false, /* |-------------------------------------------------------------------------- @@ -96,14 +96,14 @@ | */ - 'dates' => array( + 'dates' => [ /* |-------------------------------------------------------------------------- | Enable/disable date formatting |-------------------------------------------------------------------------- */ - 'enabled' => true, + 'enabled' => true, /* |-------------------------------------------------------------------------- @@ -113,22 +113,22 @@ | If set to false, a carbon object will return | */ - 'format' => false, + 'format' => false, /* |-------------------------------------------------------------------------- | Date columns |-------------------------------------------------------------------------- */ - 'columns' => array() - ), + 'columns' => [] + ], /* |-------------------------------------------------------------------------- | Import sheets by config |-------------------------------------------------------------------------- */ - 'sheets' => array( + 'sheets' => [ /* |-------------------------------------------------------------------------- @@ -139,12 +139,12 @@ | */ - 'test' => array( + 'test' => [ 'firstname' => 'A2' - ) + ] - ) + ] -); \ No newline at end of file +]; \ No newline at end of file diff --git a/src/config/views.php b/src/config/views.php index 3e5800f06..09165a911 100644 --- a/src/config/views.php +++ b/src/config/views.php @@ -1,6 +1,6 @@ array( + 'styles' => [ /* |-------------------------------------------------------------------------- | Table headings |-------------------------------------------------------------------------- */ - 'th' => array( - 'font' => array( - 'bold' => true, - 'size' => 12, - ) - ), + 'th' => [ + 'font' => [ + 'bold' => true, + 'size' => 12, + ] + ], /* |-------------------------------------------------------------------------- | Strong tags |-------------------------------------------------------------------------- */ - 'strong' => array( - 'font' => array( - 'bold' => true, - 'size' => 12, - ) - ), + 'strong' => [ + 'font' => [ + 'bold' => true, + 'size' => 12, + ] + ], /* |-------------------------------------------------------------------------- | Bold tags |-------------------------------------------------------------------------- */ - 'b' => array( - 'font' => array( - 'bold' => true, - 'size' => 12, - ) - ), + 'b' => [ + 'font' => [ + 'bold' => true, + 'size' => 12, + ] + ], /* |-------------------------------------------------------------------------- | Italic tags |-------------------------------------------------------------------------- */ - 'i' => array( - 'font' => array( - 'italic' => true, - 'size' => 12, - ) - ), + 'i' => [ + 'font' => [ + 'italic' => true, + 'size' => 12, + ] + ], /* |-------------------------------------------------------------------------- | Heading 1 |-------------------------------------------------------------------------- */ - 'h1' => array( - 'font' => array( - 'bold' => true, - 'size' => 24, - ) - ), + 'h1' => [ + 'font' => [ + 'bold' => true, + 'size' => 24, + ] + ], /* |-------------------------------------------------------------------------- | Heading 2 |-------------------------------------------------------------------------- */ - 'h2' => array( - 'font' => array( - 'bold' => true, - 'size' => 18, - ) - ), + 'h2' => [ + 'font' => [ + 'bold' => true, + 'size' => 18, + ] + ], /* |-------------------------------------------------------------------------- | Heading 2 |-------------------------------------------------------------------------- */ - 'h3' => array( - 'font' => array( - 'bold' => true, - 'size' => 13.5, - ) - ), - - /* - |-------------------------------------------------------------------------- - | Heading 4 - |-------------------------------------------------------------------------- - */ - 'h4' => array( - 'font' => array( - 'bold' => true, - 'size' => 12, - ) - ), - - /* - |-------------------------------------------------------------------------- - | Heading 5 - |-------------------------------------------------------------------------- - */ - 'h5' => array( - 'font' => array( - 'bold' => true, - 'size' => 10, - ) - ), - - /* - |-------------------------------------------------------------------------- - | Heading 6 - |-------------------------------------------------------------------------- - */ - 'h6' => array( - 'font' => array( - 'bold' => true, - 'size' => 7.5, - ) - ), - - /* - |-------------------------------------------------------------------------- - | Hyperlinks - |-------------------------------------------------------------------------- - */ - 'a' => array( - 'font' => array( + 'h3' => [ + 'font' => [ + 'bold' => true, + 'size' => 13.5, + ] + ], + + /* + |-------------------------------------------------------------------------- + | Heading 4 + |-------------------------------------------------------------------------- + */ + 'h4' => [ + 'font' => [ + 'bold' => true, + 'size' => 12, + ] + ], + + /* + |-------------------------------------------------------------------------- + | Heading 5 + |-------------------------------------------------------------------------- + */ + 'h5' => [ + 'font' => [ + 'bold' => true, + 'size' => 10, + ] + ], + + /* + |-------------------------------------------------------------------------- + | Heading 6 + |-------------------------------------------------------------------------- + */ + 'h6' => [ + 'font' => [ + 'bold' => true, + 'size' => 7.5, + ] + ], + + /* + |-------------------------------------------------------------------------- + | Hyperlinks + |-------------------------------------------------------------------------- + */ + 'a' => [ + 'font' => [ 'underline' => true, - 'color' => array( 'argb' => 'FF0000FF'), - ) - ), + 'color' => ['argb' => 'FF0000FF'], + ] + ], - /* - |-------------------------------------------------------------------------- - | Horizontal rules - |-------------------------------------------------------------------------- - */ - 'hr' => array( - 'borders' => array( - 'bottom' => array( + /* + |-------------------------------------------------------------------------- + | Horizontal rules + |-------------------------------------------------------------------------- + */ + 'hr' => [ + 'borders' => [ + 'bottom' => [ 'style' => 'thin', - 'color' => array('FF000000') - ), - ) - ) - ) + 'color' => ['FF000000'] + ], + ] + ] + ] -); \ No newline at end of file +]; \ No newline at end of file From 4c1184a437e08ee7b3cbc9e73b12205cc6566c2a Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 21:15:50 +0200 Subject: [PATCH 0216/1332] Docblock fix --- src/Maatwebsite/Excel/Readers/LaravelExcelReader.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php index b85bae0ee..e168cd5bb 100644 --- a/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php +++ b/src/Maatwebsite/Excel/Readers/LaravelExcelReader.php @@ -173,8 +173,8 @@ public function __construct(Filesystem $filesystem, FormatIdentifier $identifier /** * Load a file - * @param string $file - * @param bool $encoding + * @param string $file + * @param string|boolean $encoding * @return LaravelExcelReader */ public function load($file, $encoding = false) @@ -427,8 +427,8 @@ public function dd($columns = []) /** * Init the loading - * @param string $file - * @param bool $encoding + * @param string $file + * @param string|boolean $encoding * @return void */ protected function _init($file, $encoding = false) From caf0506f6bd47d7301cc0aceb0c3484d292c4b96 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 21:18:31 +0200 Subject: [PATCH 0217/1332] Update changelog --- docs/changelog/version-1.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index 036ac9442..e547be0cf 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,5 +1,20 @@ # Version 1 +### 1.1.6 + +- Provides.json fix +- DocBlock fixes +- Define Illuminate dependencies inside composer.json +- Bettter HTML rowspan handlingin views +- use new CellCollection() instead of ::make, to support Laravel 4.3 +- Workaround for long integers +- Add support to `wrap-text` in views +- Fix empty dates parsing +- Support local stylesheets in view parsing +- Push tr classes to td-children in views +- Support for dynamically appending rows to an empty sheet +- Fix separator typo in config + ### 1.1.5 - Select sheets by index with `Excel::selectSheetsByIndex(0,1)->load(...)` From c35a3b816564a9470e3242d07975e17bd58650a4 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 21:19:55 +0200 Subject: [PATCH 0218/1332] Update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8925ca11b..26dd1f589 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Laravel Excel v1.1.5 +## Laravel Excel v1.1.6 [](http://www.maatwebsite.nl/laravel-excel/docs) From 6f60ea6ae3d5d558955d976db5ace7ab8b3d0b9c Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Wed, 10 Sep 2014 22:03:28 +0200 Subject: [PATCH 0219/1332] First setup of Request-like ExcelFile and NewExcelFile objects for constructor and method (l4.3) injection --- src/Maatwebsite/Excel/Files/ExcelFile.php | 81 ++++++++++++++++++++ src/Maatwebsite/Excel/Files/NewExcelFile.php | 59 ++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 src/Maatwebsite/Excel/Files/ExcelFile.php create mode 100644 src/Maatwebsite/Excel/Files/NewExcelFile.php diff --git a/src/Maatwebsite/Excel/Files/ExcelFile.php b/src/Maatwebsite/Excel/Files/ExcelFile.php new file mode 100644 index 000000000..3f8ad4652 --- /dev/null +++ b/src/Maatwebsite/Excel/Files/ExcelFile.php @@ -0,0 +1,81 @@ +excel = $excel; + $this->file = $this->loadFile(); + } + + /** + * Get file + * @return string + */ + abstract public function getFile(); + + /** + * Get filters + * @return array + */ + public function getFilters() + { + return []; + } + + /** + * Load the file + * @return \Maatwebsite\Excel\Readers\LaravelExcelReader + */ + public function loadFile() + { + // Load filters + $this->loadFilters(); + + // Load the file + $file = $this->excel->load( + $this->getFile() + ); + + return $file; + } + + /** + * Load the filter + * @return void + */ + protected function loadFilters() + { + $this->excel->registerFilters( + $this->getFilters() + ); + } + + /** + * Dynamically call methods + * @param string $method + * @param array $params + * @return mixed + */ + public function __call($method, $params) + { + return call_user_func_array([$this->file, $method], $params); + } +} \ No newline at end of file diff --git a/src/Maatwebsite/Excel/Files/NewExcelFile.php b/src/Maatwebsite/Excel/Files/NewExcelFile.php new file mode 100644 index 000000000..e7858e45d --- /dev/null +++ b/src/Maatwebsite/Excel/Files/NewExcelFile.php @@ -0,0 +1,59 @@ +excel = $excel; + $this->file = $this->createNewFile(); + } + + /** + * Get file + * @return string + */ + abstract public function getFilename(); + + /** + * Load the file + * @return \Maatwebsite\Excel\Readers\LaravelExcelReader + */ + public function createNewFile() + { + // Load the file + $file = $this->excel->create( + $this->getFilename() + ); + + return $file; + } + + + /** + * Dynamically call methods + * @param string $method + * @param array $params + * @return mixed + */ + public function __call($method, $params) + { + return call_user_func_array([$this->file, $method], $params); + } +} \ No newline at end of file From eb2dedb1cfe7bf0a9a9dafc2415c1cc217f73622 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 13 Sep 2014 20:28:24 +0200 Subject: [PATCH 0220/1332] Fix fromArray, fixes issue #209 --- .../Excel/Classes/LaravelExcelWorksheet.php | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php index 6c0590c40..d6a107117 100644 --- a/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php +++ b/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php @@ -437,8 +437,22 @@ public function fromArray($source = null, $nullValue = null, $startCell = false, $this->setAutoHeadingGeneration($headingGeneration); // Add the vars - $this->_addVars($source); + $this->_addVars($source, false, $nullValue, $startCell, $strictNullComparison); + return $this; + } + + /** + * Create sheet from array + * @param null $source + * @param null $nullValue + * @param bool $startCell + * @param bool $strictNullComparison + * @return $this + * @throws PHPExcel_Exception + */ + public function createSheetFromArray($source = null, $nullValue = null, $startCell = false, $strictNullComparison = false) + { if (is_array($source)) { // Convert a 1-D array to 2-D (for ease of looping) @@ -489,10 +503,13 @@ public function fromArray($source = null, $nullValue = null, $startCell = false, * Add vars to the data array * @param string $key * @param bool|string $value + * @param null $nullValue + * @param bool $startCell + * @param bool $strictNullComparison * @throws PHPExcel_Exception - * @return void + * @return void|$this */ - protected function _addVars($key, $value = false) + protected function _addVars($key, $value = false, $nullValue = null, $startCell = false, $strictNullComparison = false) { // Add array of data if (is_array($key) || $key instanceof Collection) @@ -503,11 +520,7 @@ protected function _addVars($key, $value = false) // Create excel from array without a view if (!$this->parser) { - $nullValue = $this->getDefaultNullValue(); - $startCell = $this->getDefaultStartCell(); - $strictNullComparison = $this->getDefaultStrictNullComparison(); - - return parent::fromArray($this->data, $nullValue, $startCell, $strictNullComparison); + return $this->createSheetFromArray($this->data, $nullValue, $startCell, $strictNullComparison); } } From 1d0b2a64e60d1fb7a113febf04ad357ab13c427c Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 13 Sep 2014 20:37:23 +0200 Subject: [PATCH 0221/1332] Update HTML reader, fixes issue #211 --- src/Maatwebsite/Excel/Readers/HtmlReader.php | 41 ++++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index f27678100..311955336 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -4,7 +4,7 @@ use DOMNode; use DOMText; use DOMElement; -use domDocument; +use DOMDocument; use PHPExcel_Cell; use PHPExcel_Settings; use PHPExcel_Reader_HTML; @@ -140,13 +140,20 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, } // Create a new DOM object - $dom = new domDocument; + $dom = new DOMDocument; // Check if we need to load the file or the HTML if ($isHtmlFile) { // Load HTML from file - $loaded = @$dom->loadHTMLFile($pFilename, PHPExcel_Settings::getLibXmlLoaderOptions()); + if ((version_compare(PHP_VERSION, '5.4.0') >= 0) && defined(LIBXML_DTDLOAD)) + { + $loaded = @$dom->loadHTMLFile($pFilename, PHPExcel_Settings::getLibXmlLoaderOptions()); + } + else + { + $loaded = @$dom->loadHTMLFile($pFilename); + } } else { @@ -156,7 +163,7 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, if ($loaded === false) { - throw new PHPExcel_Reader_Exception('Failed to load ', $pFilename, ' as a DOM Document'); + throw new PHPExcel_Reader_Exception('Failed to load ' . $pFilename . ' as a DOM Document'); } // Parse css @@ -369,7 +376,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & case 'hr' : // Flush the cell - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); // count ++$row; @@ -383,7 +390,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & else { $cellContent = '----------'; - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); } ++$row; @@ -400,7 +407,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Otherwise flush our existing content and move the row cursor on else { - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); ++$row; } @@ -451,7 +458,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & { $cellContent .= "\n"; $this->_processDomElement($child, $sheet, $row, $column, $cellContent); - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); // Set style if (isset($this->_formats[$child->nodeName])) @@ -463,11 +470,11 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & { if ($cellContent > '') { - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); $row += 2; } $this->_processDomElement($child, $sheet, $row, $column, $cellContent); - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); // Set style if (isset($this->_formats[$child->nodeName])) @@ -493,13 +500,13 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & { if ($cellContent > '') { - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); } ++$row; $this->_processDomElement($child, $sheet, $row, $column, $cellContent); - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); $column = 'A'; } break; @@ -508,7 +515,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & case 'table' : // Flush the cells - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); // Set the start column $column = $this->_setTableStartColumn($column); @@ -582,7 +589,7 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & case 'td' : $this->_processDomElement($child, $sheet, $row, $column, $cellContent); - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); // If we have a colspan, count the right amount of columns, else just 1 for ($w = 0; $w < $this->spanWidth; $w++) @@ -659,7 +666,7 @@ private function _releaseTableStartColumn() * @param string $cellContent * @return void */ - private function _flushCell($sheet, &$column, $row, &$cellContent) + protected function flushCell($sheet, &$column, $row, &$cellContent) { // Process merged cells list($column, $cellContent) = $this->processMergedCells($sheet, $column, $row, $cellContent); @@ -698,7 +705,7 @@ protected function _processHeadings($child, $sheet, $row, $column, $cellContent) { $this->_processDomElement($child, $sheet, $row, $column, $cellContent); - $this->_flushCell($sheet, $column, $row, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); if (isset($this->_formats[$child->nodeName])) { @@ -1302,7 +1309,7 @@ private function processMergedCells($sheet, &$column, $row, $cellContent) if (in_array($row, array_keys($this->styleForRows))) $this->styleByClass($sheet, $column, $row, $this->styleForRows[$row]); - $this->_flushCell($sheet, $newCol, $row, $cellContent); + $this->flushCell($sheet, $newCol, $row, $cellContent); } } } From cef30a20a1a58d3c57446aca7065c353ccba1a75 Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 13 Sep 2014 23:09:34 +0200 Subject: [PATCH 0222/1332] Enhanced css usages in view exports + built in support for inline style blocks, fixes issue #210 --- composer.json | 3 +- .../Excel/ExcelServiceProvider.php | 18 +- src/Maatwebsite/Excel/Parsers/CssParser.php | 166 +++-------------- src/Maatwebsite/Excel/Readers/HtmlReader.php | 172 ++++++++---------- 4 files changed, 121 insertions(+), 238 deletions(-) diff --git a/composer.json b/composer.json index a8eb92728..4f2f2113c 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,8 @@ "illuminate/support": "~4.0", "illuminate/routing": "~4.0", "illuminate/view": "~4.0", - "nesbot/carbon": "~1.0" + "nesbot/carbon": "~1.0", + "tijsverkoyen/css-to-inline-styles": "~1.5" }, "require-dev": { "phpunit/phpunit": "~4.0", diff --git a/src/Maatwebsite/Excel/ExcelServiceProvider.php b/src/Maatwebsite/Excel/ExcelServiceProvider.php index e36a25f4d..fdb1959b9 100644 --- a/src/Maatwebsite/Excel/ExcelServiceProvider.php +++ b/src/Maatwebsite/Excel/ExcelServiceProvider.php @@ -7,11 +7,12 @@ use Illuminate\Support\Facades\Config; use Maatwebsite\Excel\Classes\PHPExcel; use Illuminate\Support\ServiceProvider; +use Maatwebsite\Excel\Parsers\CssParser; use Maatwebsite\Excel\Parsers\ViewParser; use Maatwebsite\Excel\Classes\FormatIdentifier; use Maatwebsite\Excel\Readers\LaravelExcelReader; use Maatwebsite\Excel\Writers\LaravelExcelWriter; -use Maatwebsite\Excel\Classes\LaravelExcelWorksheet; +use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles; /** * @@ -56,6 +57,7 @@ public function boot() public function register() { $this->bindClasses(); + $this->bindCssParser(); $this->bindReaders(); $this->bindParsers(); $this->bindPHPExcelClass(); @@ -87,6 +89,18 @@ protected function bindPHPExcelClass() }); } + /** + * Bind the css parser + */ + protected function bindCssParser() + { + // Bind css parser + $this->app->bindShared('excel.parsers.css', function($app) + { + return new CssParser(new CssToInlineStyles()); + }); + } + /** * Bind writers * @return void @@ -102,7 +116,7 @@ protected function bindReaders() // Bind the html reader class $this->app['excel.readers.html'] = $this->app->share(function ($app) { - return new Html(); + return new Html($app['excel.parsers.css']); }); } diff --git a/src/Maatwebsite/Excel/Parsers/CssParser.php b/src/Maatwebsite/Excel/Parsers/CssParser.php index 21ee51027..f7d2976d5 100644 --- a/src/Maatwebsite/Excel/Parsers/CssParser.php +++ b/src/Maatwebsite/Excel/Parsers/CssParser.php @@ -1,6 +1,8 @@ dom = $dom; - $this->findStyleSheets()->parse(); + $this->cssInliner = $cssInliner; } /** - * Lookup the class or id - * @param string $type - * @param string $name - * @return array + * Transform the found css to inline styles */ - public function lookup($type, $name) + public function transformCssToInlineStyles($html) { - switch ($type) - { - case 'id': - $name = '#' . $name; - break; + // Clean-up html + $this->cssInliner->setCleanup(true); - case 'class': - $name = '.' . $name; - break; - } - - // Get the css - $results = $this->toArray(); + // Set html + $this->cssInliner->setHtml($html); - // Return the css if known - if (isset($results[$name])) - return $results[$name]; + // Use inline style blocks + $this->cssInliner->setUseInlineStylesBlock(true); - return []; - } + // Loop through all stylesheets + foreach($this->links as $link) + { + $css = file_get_contents($link); + $this->cssInliner->setCSS($css); + } - /** - * Return array with CSS attributes - * @return array - */ - public function toArray() - { - return $this->results; + return $this->cssInliner->convert(); } /** * Find the stylesheets inside the view + * @param DOMDocument $dom * @return CssParser */ - protected function findStyleSheets() + public function findStyleSheets(DOMDocument $dom) { // Import the dom - $this->importDom(); + $this->importDom($dom); // Get all stylesheet tags $tags = $this->getStyleSheetTags(); @@ -123,91 +91,13 @@ protected function findStyleSheets() return $this; } - /** - * Parse the links to css - * @return void - */ - protected function parse() - { - foreach ($this->links as $link) - { - $css = $this->getCssFromLink($link); - $this->breakCSSToPHP($css); - } - } - - /** - * Break CSS into a PHP array - * @param string $css - * @return void - */ - protected function breakCSSToPHP($css) - { - $results = []; - - preg_match_all($this->matcher, $css, $matches); - - foreach ($matches[0] as $i => $original) - { - if (!starts_with($original, '@')) // ignore attributes starting with @ (like @import) - $this->breakIntoAttributes($i, $matches); - } - } - - /** - * Break css into attributes - * @param integer $i - * @param array $matches - * @return void - */ - protected function breakIntoAttributes($i, $matches) - { - // Seperate attributes - $attributes = explode(';', $matches[2][$i]); - - foreach ($attributes as $attribute) - { - $this->breakIntoProperties($attribute, $i, $matches); - } - } - - /** - * Break into css properties - * @param string $attribute - * @param integer $i - * @param array $matches - * @return void - */ - protected function breakIntoProperties($attribute, $i, $matches) - { - if (strlen(trim($attribute)) > 0) // for missing semicolon on last element, which is legal - { - // List properties with name and value - list($name, $value) = explode(':', $attribute); - $this->results[$matches[1][$i]][trim($name)] = $this->cleanValue($value); - } - } - - /** - * Return a clean value - * @param string $value - * @return string - */ - protected function cleanValue($value) - { - $value = trim($value); - $value = str_replace('!important', '', $value); - - return trim($value); - } - /** * Import the dom * @return SimpleXMLElement */ - protected function importDom() + protected function importDom(DOMDocument $dom) { - return $this->xml = simplexml_import_dom($this->dom); + return $this->xml = simplexml_import_dom($dom); } /** diff --git a/src/Maatwebsite/Excel/Readers/HtmlReader.php b/src/Maatwebsite/Excel/Readers/HtmlReader.php index 311955336..0d26b23bc 100644 --- a/src/Maatwebsite/Excel/Readers/HtmlReader.php +++ b/src/Maatwebsite/Excel/Readers/HtmlReader.php @@ -33,9 +33,10 @@ class Html extends PHPExcel_Reader_HTML { /** + * Style per range * @var array */ - protected $styleForRows = []; + protected $styles = []; /** * Input encoding @@ -67,6 +68,20 @@ class Html extends PHPExcel_Reader_HTML { */ protected $spanHeight = 1; + /** + * @var + */ + private $cssParser; + + /** + * @param CssParser $cssParser + */ + public function __construct(CssParser $cssParser) + { + $this->cssParser = $cssParser; + parent::__construct(); + } + /** * Loads PHPExcel from file * @@ -125,7 +140,6 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, // Double check if it's a file if (is_file($pFilename)) { - $isHtmlFile = true; $this->_openFile($pFilename); @@ -158,7 +172,19 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, else { // Load HTML from string - $loaded = @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8')); + @$dom->loadHTML(mb_convert_encoding($pFilename, 'HTML-ENTITIES', 'UTF-8')); + + // Let the css parser find all stylesheets + $this->cssParser->findStyleSheets($dom); + + // Transform the css files to inline css and replace the html + $html = $this->cssParser->transformCssToInlineStyles($pFilename); + + // Re-init dom doc + $dom = new DOMDocument; + + // Load again with css included + $loaded = @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); } if ($loaded === false) @@ -166,9 +192,6 @@ public function loadIntoExistingSheet($pFilename, LaravelExcelWorksheet $sheet, throw new PHPExcel_Reader_Exception('Failed to load ' . $pFilename . ' as a DOM Document'); } - // Parse css - $this->css = new CssParser($dom); - // Discard white space $dom->preserveWhiteSpace = true; @@ -223,10 +246,8 @@ public function autosizeColumn($sheet) */ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, &$cellContent) { - foreach ($element->childNodes as $child) { - // If is text if ($child instanceof DOMText) { @@ -245,9 +266,9 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & { $attributeArray = []; - // If it's a column, and it's row has a class, style it - if (in_array($row, array_keys($this->styleForRows))) - $this->styleByClass($sheet, $column, $row, $this->styleForRows[$row]); + // Set row (=parent) styles + if(isset($this->styles[$row])) + $this->parseInlineStyles($sheet, $column, $row, $this->styles[$row]); // Loop through the child's attributes foreach ($child->attributes as $attribute) @@ -258,12 +279,6 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Attribute names switch ($attribute->name) { - - // Inline css styles - case 'style': - $this->parseInlineStyles($sheet, $column, $row, $attribute->value); - break; - // Colspan case 'width': $this->parseWidth($sheet, $column, $row, $attribute->value); @@ -275,12 +290,12 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Colspan case 'colspan': - $this->parseColSpan($sheet, $column, $row, $attribute->value); + $this->parseColSpan($sheet, $column, $row, $attribute->value, $child->attributes); break; // Rowspan case 'rowspan': - $this->parseRowSpan($sheet, $column, $row, $attribute->value); + $this->parseRowSpan($sheet, $column, $row, $attribute->value, $child->attributes); break; // Alignment @@ -293,19 +308,12 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & $this->parseValign($sheet, $column, $row, $attribute->value); break; - // Classes - case 'class': - - // If it's a tr, remember the row number - if ($child->nodeName == 'tr') - $this->styleForRows[$row] = $attribute->value; - - $this->styleByClass($sheet, $column, $row, $attribute->value); - break; + // Inline css styles + case 'style': + $this->parseInlineStyles($sheet, $column, $row, $attribute->value); - // Ids - case 'id': - $this->styleById($sheet, $column, $row, $attribute->value); + if($child->nodeName == 'tr') + $this->styles[$row] = $attribute->value; break; } } @@ -570,7 +578,6 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Table heading case 'th' : - // Continue processing $this->_processHeadings($child, $sheet, $row, $column, $cellContent); @@ -587,7 +594,6 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // Table cell case 'td' : - $this->_processDomElement($child, $sheet, $row, $column, $cellContent); $this->flushCell($sheet, $column, $row, $cellContent); @@ -599,7 +605,6 @@ private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, & // reset the span width after the process $this->spanWidth = 1; - break; // Html Body @@ -703,7 +708,6 @@ protected function flushCell($sheet, &$column, $row, &$cellContent) */ protected function _processHeadings($child, $sheet, $row, $column, $cellContent) { - $this->_processDomElement($child, $sheet, $row, $column, $cellContent); $this->flushCell($sheet, $column, $row, $cellContent); @@ -715,55 +719,6 @@ protected function _processHeadings($child, $sheet, $row, $column, $cellContent) return $sheet; } - /** - * Style the element by class - * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $class - * @return void - */ - protected function styleByClass($sheet, $column, $row, $class) - { - // If the class has a whitespace - // break into multiple classes - if (str_contains($class, ' ')) - { - $classes = explode(' ', $class); - foreach ($classes as $class) - { - return $this->styleByClass($sheet, $column, $row, $class); - } - } - - // Lookup the css - $styles = $this->css->lookup('class', $class); - - // Loop through the styles - foreach ($styles as $name => $value) - { - $this->parseCssProperties($sheet, $column, $row, $name, $value); - } - } - - /** - * Style the element by class - * @param LaravelExcelWorksheet $sheet - * @param string $column - * @param integer $row - * @param string $class - * @return void - */ - protected function styleById($sheet, $column, $row, $class) - { - $styles = $this->css->lookup('id', $class); - - foreach ($styles as $name => $value) - { - $this->parseCssProperties($sheet, $column, $row, $name, $value); - } - } - /** * Insert a image inside the sheet * @param LaravelExcelWorksheet $sheet @@ -834,9 +789,10 @@ protected function parseHeight($sheet, $column, $row, $height) * @param string $column * @param integer $row * @param integer $spanWidth + * @param $attributes * @return void */ - protected function parseColSpan($sheet, $column, $row, $spanWidth) + protected function parseColSpan($sheet, $column, $row, $spanWidth, $attributes) { $startCell = $column . $row; @@ -854,6 +810,15 @@ protected function parseColSpan($sheet, $column, $row, $spanWidth) // Set range $range = $startCell . ':' . $endCell; + // Remember css inline styles + foreach($attributes as $attribute) + { + if($attribute->name == 'style') + { + $this->styles[$range] = $attribute->value; + } + } + // Merge the cells $sheet->mergeCells($range); } @@ -864,9 +829,10 @@ protected function parseColSpan($sheet, $column, $row, $spanWidth) * @param string $column * @param integer $row * @param integer $spanHeight + * @param $attributes * @return void */ - protected function parseRowSpan($sheet, $column, $row, $spanHeight) + protected function parseRowSpan($sheet, $column, $row, $spanHeight, $attributes) { // Set the span height $this->spanHeight = --$spanHeight; @@ -878,6 +844,15 @@ protected function parseRowSpan($sheet, $column, $row, $spanHeight) $endCell = $column . ($row + $this->spanHeight); $range = $startCell . ':' . $endCell; + // Remember css inline styles + //foreach($attributes as $attribute) + //{ + // if($attribute->name == 'style') + // { + // $this->styles[$range] = $attribute->value; + // } + //} + // Merge the cells $sheet->mergeCells($range); } @@ -1023,17 +998,19 @@ protected function parseCssProperties($sheet, $column, $row, $name, $value) // BACKGROUND case 'background': case 'background-color': + + $original = $value; + $value = $this->getColor($value); - $cells->applyFromArray( + $cells->getFill()->applyFromArray( [ - 'fill' => [ - 'type' => PHPExcel_Style_Fill::FILL_SOLID, - 'color' => ['rgb' => $value] - ] + 'type' => PHPExcel_Style_Fill::FILL_SOLID, + 'color' => ['rgb' => $value] ] ); - break; + + break; // TEXT COLOR case 'color': @@ -1303,17 +1280,18 @@ private function processMergedCells($sheet, &$column, $row, $cellContent) $newCol = PHPExcel_Cell::stringFromColumnIndex( (PHPExcel_Cell::columnIndexFromString($column) + 1) - 1 ); + $column = $newCol; - // If it's a column, and it's row has a class, style it - if (in_array($row, array_keys($this->styleForRows))) - $this->styleByClass($sheet, $column, $row, $this->styleForRows[$row]); + // Set style for merged cells + if(isset($this->styles[$row])) + $this->parseInlineStyles($sheet, $column, $row, $this->styles[$row]); - $this->flushCell($sheet, $newCol, $row, $cellContent); + // Flush cell + $this->flushCell($sheet, $column, $row, $cellContent); } } } - return [$column, $cellContent]; } } \ No newline at end of file From 3892fa72d131166019be720a4b2b0ae55ac12e7c Mon Sep 17 00:00:00 2001 From: Patrick Brouwers Date: Sat, 13 Sep 2014 23:21:16 +0200 Subject: [PATCH 0223/1332] Update docs + changelog --- README.md | 4 ++-- docs/blade/styling.md | 15 ++++++++++++--- docs/changelog/version-1.md | 15 ++++++++++++--- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 26dd1f589..29ba72ad3 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ -## Laravel Excel v1.1.6 +## Laravel Excel v1.1.7 [](http://www.maatwebsite.nl/laravel-excel/docs) Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 4.* with a touch of the Laravel Magic. It includes features like: importing Excel and CSV to collections, exporting models, array's and views to Excel, importing batches of files and importing a file by a config file. - Import into Laravel **Collections** -- Export **Blade views** to Excel and CSV +- Export **Blade views** to Excel and CSV with optional CSS styling - **Batch** imports - A lot of optional **config settings** - Easy **cell caching** diff --git a/docs/blade/styling.md b/docs/blade/styling.md index 7c37bfcfc..b257d3924 100644 --- a/docs/blade/styling.md +++ b/docs/blade/styling.md @@ -92,8 +92,7 @@ It's possible to use inline styles inside your view files. Most of the general s ### Styling through external CSS file -**Basic** styling can be done through an external CSS file. -At this moment nested CSS is **not** supported yet. Only direct class and ID references will work. +Styling can be done through an external CSS file. External css file: @@ -107,6 +106,14 @@ External css file: color: #ffffff; } + tr td { + background-color: #ffffff; + } + + tr > td { + border-bottom: 1px solid #000000; + } + Table: @@ -121,4 +128,6 @@ Table: -> Inside the reference guide you can find a list of supported styles. \ No newline at end of file +> Inside the reference guide you can find a list of supported styles. + +> It's advised to include `` into the view to fix problems with UTF-8 encoding. \ No newline at end of file diff --git a/docs/changelog/version-1.md b/docs/changelog/version-1.md index e547be0cf..f4d33b0da 100644 --- a/docs/changelog/version-1.md +++ b/docs/changelog/version-1.md @@ -1,18 +1,27 @@ # Version 1 +### 1.1.7 +- Fix heading generation for export with `->fromArray()` +- Bugfix for non-Unix kernels +- Enhanced CSS parser (thanks to `tijsverkoyen/CssToInlineStyles`) +- Support for nested CSS styles +- Support for multiple css attributes per class +- Support for internal and external CSS files +- Support for inline style blocks (`