Function to Read xls(x) file

  define( 'ABSPATH', true );
  include 'inc/simplexlsx.class.php';
  require_once 'inc/excel_reader2.php';

  $file = $form_state['storage']['file'];
  $file->status = FILE_STATUS_PERMANENT;
  $filepath = drupal_realpath($form_state['storage']['file']->uri);

  ################### mapping of excel readers ###################
    $ext = pathinfo($filepath, PATHINFO_EXTENSION);
  ################################################################

  $output = array();
  //extension logic starts here
  $xlsx_rw = NULL;

  switch ($ext) {
    case 'xls':
      $xlsx_rw = 2;
      $data = new Spreadsheet_Excel_Reader($filepath);
      $numrows = count($data->sheets[0]['cells']);
      $numcols = $data->sheets[0]['numCols']; 
      //xls start from zero 0
      for($row = 2; $row <= $numrows; $row++){
        for ($col = 1; $col <= $numcols; $col++) {
          $temp_val = $data->val($row, $col, $sheet = 0);
          if( !empty($columns[$col]) && !empty($temp_val) ) {
            if (($col==1||$col==8||$col==13||$col==14) && gettype($temp_val)!='integer') {
              if (strpos($temp_val, ']') !== FALSE && strpos($temp_val, '-') !== FALSE) {
                // Remove specific formatting for Numbers, since it exists as per above condition
                $temp_val = explode(']', $temp_val);
                $temp_val = explode('-', $temp_val[0]);
                $temp_val = $temp_val[1];              
                $output[$row][$columns[$col]] = isset($temp_val)?(int)$temp_val:0;
              } else {
                $output[$row][$columns[$col]] = isset($temp_val)?(int)$temp_val:0;
              }
            } else {
              $output[$row][$columns[$col]] = $temp_val;
            }
          }  
        }          
      }
      break;
    case 'xlsx':
      $xlsx_rw = 1;
      $data = new SimpleXLSX($filepath);
      $test =  list($numcols, $numrows) = $data->dimension();
      $info = $data->rows();
      //xlsx start from zero 0
      for($r = 1; $r < $numrows; $r++){
        $row = $r;
        foreach($info[$r] as $col => $cols){
          if(!empty($columns[$col])){
            $output[$row][$columns[$col]] = $cols;
          }  
        }
      }
      break;
    default:
      # code...
      break;
  }

print_r($output);

Add new comment