You are here

function _phpexcel_set_columns in PHPExcel 7.3

Same name and namespace in other branches
  1. 8.3 phpexcel.inc \_phpexcel_set_columns()
  2. 6.2 phpexcel.api.inc \_phpexcel_set_columns()
  3. 6 phpexcel.api.inc \_phpexcel_set_columns()
  4. 7 phpexcel.api.inc \_phpexcel_set_columns()
  5. 7.2 phpexcel.inc \_phpexcel_set_columns()

Adds the data to the Excel file.

See also

phpexcel_export()

1 call to _phpexcel_set_columns()
phpexcel_export in ./phpexcel.inc
Simple API function which will generate an XLS file and save it in $path.

File

./phpexcel.inc, line 289
Defines the phpexcel api functions that other modules can use.

Code

function _phpexcel_set_columns($xls, &$data, $headers = NULL, $options = array()) {

  // Prior to PHP 5.3, calling current() on an associative array would not work.
  // Get only array values, just in case.
  if (!is_array(current(current(array_values($data))))) {
    $data = array(
      $data,
    );
  }
  phpexcel_invoke('export', 'data', $data, $xls, $options);
  $sheet_id = 0;
  foreach ($data as $sheet_name => $sheet_data) {

    // If the sheet name is just an index, assume to create a string name
    if (is_numeric($sheet_name)) {
      $sheet_name = t('Worksheet !id', array(
        '!id' => $sheet_id + 1,
      ));
    }

    // First, attempt to open an existing sheet by the given name.
    if (($sheet = $xls
      ->getSheetByName($sheet_name)) === NULL) {

      // If the headers are not set, we haven't created any sheets yet.
      // Create them now.
      if (!isset($headers)) {
        if ($sheet_id) {
          $xls
            ->createSheet($sheet_id);
          $sheet = $xls
            ->setActiveSheetIndex($sheet_id);
        }
        else {

          // PHPExcel always creates one sheet.
          $sheet = $xls
            ->getSheet();
        }
        $sheet
          ->setTitle($sheet_name);
        phpexcel_invoke('export', 'new sheet', $sheet_id, $xls, $options);
      }
      else {
        $sheet = $xls
          ->setActiveSheetIndex($sheet_id);
      }
    }

    // Get the highest row of the sheet to calculate the offset so that rows are
    // simply appended rather than overwritten if the file is built in multiple
    // passes.
    $offset = $sheet
      ->getHighestRow() + ($options['ignore_headers'] ? 0 : 1);
    for ($i = 0, $len = count($sheet_data); $i < $len; $i++) {
      for ($j = 0; $j < count($sheet_data[$i]); $j++) {
        $value = isset($sheet_data[$i][$j]) ? $sheet_data[$i][$j] : '';

        // We must offset the row count (by 2 if the first row is used by the
        // headers, because PHPExcel starts the count at 1, not 0).
        phpexcel_invoke('export', 'pre cell', $value, $sheet, $options, $j, $i + $offset);
        $sheet
          ->setCellValueByColumnAndRow($j, $i + $offset, $value);
        phpexcel_invoke('export', 'post cell', $value, $sheet, $options, $j, $i + $offset);
      }
    }
    $sheet_id++;
  }
}