generate an XLS(X) file from an array
963870
public static function buildAndGetDocument(array $content) :string {
		// if !class_exists... a little help for the developer
		if(!class_exists('\PhpOffice\PhpSpreadsheet\Spreadsheet')) {
			Throw new \Polyfony\Exception(
				'Responses of type XLS(X) depend on phpoffice/spreadsheet', 
				500
			);
		}
		// create a new spreadsheet 
		$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet;
		// to to the current sheet
		($spreadsheet->getActiveSheet())
			// and import our array
			->fromArray(Query\Convert::convertArrayOfObjectsToPlainArray($content), NULL, 'A1');
		// create a singleton to generate an actual file
		$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xls($spreadsheet);
		// as dirty as it may be, we have to buffer it, since phpoffice 
		// doesn't even support gettint the document without saving or outputing it
		ob_start();
		// generate it
		$writer->save('php://output');
		// return the formatted document
		return ob_get_clean();
	}
159040
def _mergex(xlo, xhi):
    
    N = xlo.size
    x = np.zeros(N + 1)
    x[:N] = xlo.copy()
    x[-1] = xhi[-1]

    return x
1318634
function _gpfArraySlice (array, from, to) {
    return Array.prototype.slice.call(array, from, to || array.length);
}
1227700
def _format_array(x, fmt):
    # type: (Any, str) -> str
    
    value_repr = ", ".join(fmt.format(v) for v in x)
    return "[{}]".format(value_repr)
1102316
def _call(self, x, out):
        """"""
        with writable_array(out) as out_arr:
            resize_array(x.asarray(), self.range.shape, offset=self.offset,
                         pad_mode=self.pad_mode, pad_const=self.pad_const,
                         direction='forward', out=out_arr)
311132
def export_to_xls(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
    """"""

    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet(sheet_name)

    prepared_table = prepare_to_export(table, *args, **kwargs)

    field_names = next(prepared_table)
    for column_index, field_name in enumerate(field_names):
        sheet.write(0, column_index, field_name)

    _convert_row = _python_to_xls([table.fields.get(field) for field in field_names])
    for row_index, row in enumerate(prepared_table, start=1):
        for column_index, (value, data) in enumerate(_convert_row(row)):
            sheet.write(row_index, column_index, value, **data)

    return_result = False
    if filename_or_fobj is None:
        filename_or_fobj = BytesIO()
        return_result = True

    source = Source.from_file(filename_or_fobj, mode="wb", plugin_name="xls")
    workbook.save(source.fobj)
    source.fobj.flush()

    if return_result:
        source.fobj.seek(0)
        result = source.fobj.read()
    else:
        result = source.fobj

    if source.should_close:
        source.fobj.close()

    return result
780223
function parse_Array(blob, length, opts) {
	var ref = parse_Ref(blob, 6);
	/* TODO: fAlwaysCalc */
	switch(opts.biff) {
		case 2: blob.l ++; length -= 7; break;
		case 3: case 4: blob.l += 2; length -= 8; break;
		default: blob.l += 6; length -= 12;
	}
	return [ref, parse_ArrayParsedFormula(blob, length, opts, ref)];
}
700187
def _code2xls(self, worksheets):
        

        code_array = self.code_array

        xls_max_shape = self.xls_max_rows, self.xls_max_cols, self.xls_max_tabs

        for key in code_array:
            if all(kele < mele for kele, mele in zip(key, xls_max_shape)):
                # Cell lies within Excel boundaries
                row, col, tab = key
                code_str = code_array(key)
                if code_str is not None:
                    style = self._get_xfstyle(worksheets, key)
                    worksheets[tab].write(row, col, label=code_str,
                                          style=style)

        # Handle cell formatting in cells without code

        # Get bboxes for all cell_attributes
        max_shape = [min(xls_max_shape[0], code_array.shape[0]),
                     min(xls_max_shape[1], code_array.shape[1])]

        # Prevent systems from blocking
        if max_shape[0] * max_shape[1] > 1024000:
            # Ignore all cell attributes below row 3999
            max_shape[0] = 4000

        cell_attributes = code_array.dict_grid.cell_attributes
        bboxes = []
        for s, __tab, __ in cell_attributes:
            if s:
                bboxes.append((s.get_grid_bbox(code_array.shape), __tab))

        # Get bbox_cell_set from bboxes
        cells = []
        for ((bb_top, bb_left), (bb_bottom, bb_right)), __tab in bboxes:
            __bb_bottom = min(bb_bottom, max_shape[0])
            __bb_right = min(bb_right, max_shape[1])
            for __row, __col in product(xrange(bb_top, __bb_bottom + 1),
                                        xrange(bb_left, __bb_right + 1)):
                cells.append((__row, __col, __tab))

        cell_set = set(cells)
        # Loop over those with non-standard attributes
        for key in cell_set:
            if key not in code_array and all(ele >= 0 for ele in key):
                row, col, tab = key
                style = self._get_xfstyle(worksheets, key)
                worksheets[tab].write(row, col, label="", style=style)
87417
function exportJson(args) {

    if (typeof args === 'undefined' || args.length == 0) {
        glob(config.xlsx.src, function(err, files) {
            if (err) {
                console.error("exportJson error:", err);
                throw err;
            };

            files.forEach(function(element, index, array) {
                xlsx.toJson(path.join(__dirname, element), path.join(__dirname, config.xlsx.dest), config.xlsx.head,config.xlsx.arraySeparator);
            });

        })
    } else {
        if (args instanceof Array) {
            args.forEach(function(element, index, array) {
                xlsx.toJson(path.join(__dirname, element), path.join(__dirname, config.xlsx.dest), config.xlsx.head,config.xlsx.arraySeparator);
            });
        };
    }
}
1218982
def wr_xlsx(self, fout_xlsx, goea_results, **kws):
        """"""
        # kws: prt_if indent itemid2name(study_items)
        objprt = PrtFmt()
        prt_flds = kws.get('prt_flds', self.get_prtflds_default(goea_results))
        xlsx_data = MgrNtGOEAs(goea_results).get_goea_nts_prt(prt_flds, **kws)
        if 'fld2col_widths' not in kws:
            kws['fld2col_widths'] = {f:objprt.default_fld2col_widths.get(f, 8) for f in prt_flds}
        RPT.wr_xlsx(fout_xlsx, xlsx_data, **kws)
71069
def excel_todictlist(path_to_file, **kwargs):
    
    result = collections.OrderedDict()
    encoding = kwargs.get('encoding', 'utf-8')
    formatting_info = '.xlsx' not in path_to_file
    count = 0

    with xlrd.open_workbook(
        path_to_file,
        encoding_override=encoding, formatting_info=formatting_info) \
            as _excelfile:

        for sheet_name_raw in _excelfile.sheet_names():

            # if empty sheet name put sheet# as name
            sheet_name = sheet_name_raw or "sheet{}".format(count)
            result[sheet_name] = []

            xl_sheet = _excelfile.sheet_by_name(sheet_name_raw)

            for row_idx in range(0, xl_sheet.nrows):
                col_data = []
                for col_idx in range(0, xl_sheet.ncols):

                    # Get cell object by row, col
                    cell_obj = xl_sheet.cell(row_idx, col_idx)
                    merged_info = is_merged(xl_sheet, row_idx, col_idx)

                    # Search for value in merged_info
                    if not cell_obj.value and merged_info:
                        cell_obj = search_mergedcell_value(
                            xl_sheet, merged_info[1])
                        col_data.append(cell_obj.value if cell_obj else '')
                    else:
                        col_data.append(cell_obj.value)

                result[sheet_name].append(col_data)

            count += 1  # increase sheet counter

    return result
883399
function prepareSheet(opts, data, columns, idx) {
		/** Default options for sheet */
		var opt = {sheetid: 'Sheet ' + idx, headers: true};
		alasql.utils.extend(opt, opts);

		var dataLength = Object.keys(data).length;

		// Generate columns if they are not defined
		if ((!columns || columns.length == 0) && dataLength > 0) {
			columns = Object.keys(data[0]).map(function(columnid) {
				return {columnid: columnid};
			});
		}

		var cells = {};

		if (wb.SheetNames.indexOf(opt.sheetid) > -1) {
			cells = wb.Sheets[opt.sheetid];
		} else {
			wb.SheetNames.push(opt.sheetid);
			wb.Sheets[opt.sheetid] = {};
			cells = wb.Sheets[opt.sheetid];
		}

		var range = 'A1';
		if (opt.range) range = opt.range;

		var col0 = alasql.utils.xlscn(range.match(/[A-Z]+/)[0]);
		var row0 = +range.match(/[0-9]+/)[0] - 1;

		if (wb.Sheets[opt.sheetid]['!ref']) {
			var rangem = wb.Sheets[opt.sheetid]['!ref'];
			var colm = alasql.utils.xlscn(rangem.match(/[A-Z]+/)[0]);
			var rowm = +rangem.match(/[0-9]+/)[0] - 1;
		} else {
			var colm = 1,
				rowm = 1;
		}
		var colmax = Math.max(col0 + columns.length, colm);
		var rowmax = Math.max(row0 + dataLength + 2, rowm);

		//		console.log(col0,row0);
		var i = row0 + 1;

		wb.Sheets[opt.sheetid]['!ref'] = 'A1:' + alasql.utils.xlsnc(colmax) + rowmax;
		//		var i = 1;

		if (opt.headers) {
			columns.forEach(function(col, idx) {
				cells[alasql.utils.xlsnc(col0 + idx) + '' + i] = {v: col.columnid.trim()};
			});
			i++;
		}

		for (var j = 0; j < dataLength; j++) {
			columns.forEach(function(col, idx) {
				var cell = {v: data[j][col.columnid]};
				if (typeof data[j][col.columnid] == 'number') {
					cell.t = 'n';
				} else if (typeof data[j][col.columnid] == 'string') {
					cell.t = 's';
				} else if (typeof data[j][col.columnid] == 'boolean') {
					cell.t = 'b';
				} else if (typeof data[j][col.columnid] == 'object') {
					if (data[j][col.columnid] instanceof Date) {
						cell.t = 'd';
					}
				}
				cells[alasql.utils.xlsnc(col0 + idx) + '' + i] = cell;
			});
			i++;
		}
	}
495385
public function toArray($sheet_name,$ext=false)
  {
    if(!$ext){
      $ext=pathinfo($sheet_name, PATHINFO_EXTENSION);
    }
    switch ($ext) {
      case 'csv':
      $reader = ReaderFactory::create(Type::CSV);
      break;
      case 'ods':
      $reader = ReaderFactory::create(Type::ODS);
      break;
      case 'xlsx':
      $reader = ReaderFactory::create(Type::XLSX);
      break;
    }
    $reader->open($sheet_name);
    foreach ($reader->getSheetIterator() as $sheet) {
      $sheetName = $sheet->getName();
      foreach ($sheet->getRowIterator() as $row) {
        $list['lists'][$sheetName][]=$row;
      }
    }
    $reader->close();
    $lists=false;
    foreach ($list['lists'] as $key => $value) {
      $lists[$key]=$this->sheetToAlpha($value);
    }
    if($ext=="csv"){
      return $lists[""];
    }else{
      return $lists;
    }
  }
1281004
private function readXlsx()
    {
        $zipHandle = new \ZipArchive();
        $outputText = '';
        if (true === $zipHandle->open($this->filename)) {
            if (($xmlIndex = $zipHandle->locateName('xl/sharedStrings.xml')) !== false) {
                $xmlData = $zipHandle->getFromIndex($xmlIndex);
                $domDocument = new \DOMDocument();
                $domDocument->loadXML($xmlData, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
                $outputText = strip_tags(str_replace('</t>', ' </t>', $domDocument->saveXML()));
            } else {
                $outputText .= '';
            }
            $zipHandle->close();
        } else {
            $outputText .= '';
        }
        return $outputText;
    }
377328
async function toExcel(opts) {
  const { collection, documents, columns, stream, filename } = opts;
  const workbook = new Excel.stream.xlsx.WorkbookWriter({
    stream,
    filename,
    useStyles: true,
    useSharedStrings: true
  });

  workbook.created = new Date();
  workbook.modified = new Date();

  const sheet = workbook.addWorksheet('sheet 1');

  sheet.columns = columns.map(column => {
    const path = column.field;
    const namePath = collection.parsePath(path);

    return {
      header: column.label || namePath.pathLabel,
      key: path,
      width: 10
    };
  });

  for (const document of documents) {
    const row = {};

    for (const column of columns) {
      const path = column.field;
      const namePath = collection.parsePath(path);

      row[path] = namePath.get(document);
    }

    sheet.addRow(row).commit();
  }

  sheet.commit();

  await workbook.commit();
}
1272819
public static function arrayToXLS(Array $data, String $file = 'excel.xls')
    {
        $file = Base::suffix($file, '.xls');

        header("Content-Disposition: attachment; filename=\"$file\"");
        header("Content-Type: application/vnd.ms-excel;");
        header("Pragma: no-cache");
        header("Expires: 0");

        $output = fopen("php://output", 'w');

        foreach( $data as $column )
        {
            fputcsv($output, $column, "\t");
        }

        fclose($output);
    }
53163
def make_arrays(blastfile, qpadbed, spadbed, qpadnames, spadnames):
    
    m, n = len(qpadnames), len(spadnames)
    qpadorder, spadorder = qpadbed.order, spadbed.order
    qpadid = dict((a, i) for i, a in enumerate(qpadnames))
    spadid = dict((a, i) for i, a in enumerate(spadnames))
    qpadlen = dict((a, len(b)) for a, b in qpadbed.sub_beds())
    spadlen = dict((a, len(b)) for a, b in spadbed.sub_beds())

    qsize, ssize = len(qpadbed), len(spadbed)

    assert sum(qpadlen.values()) == qsize
    assert sum(spadlen.values()) == ssize

    # Populate arrays of observed counts and expected counts
    logging.debug("Initialize array of size ({0} x {1})".format(m, n))
    observed = np.zeros((m, n))
    fp = open(blastfile)
    all_dots = 0
    for row in fp:
        b = BlastLine(row)
        qi, q = qpadorder[b.query]
        si, s = spadorder[b.subject]
        qseqid, sseqid = q.seqid, s.seqid
        qsi, ssi = qpadid[qseqid], spadid[sseqid]
        observed[qsi, ssi] += 1
        all_dots += 1

    assert int(round(observed.sum())) == all_dots

    logging.debug("Total area: {0} x {1}".format(qsize, ssize))
    S = qsize * ssize
    expected = np.zeros((m, n))
    qsum = 0
    for i, a in enumerate(qpadnames):
        alen = qpadlen[a]
        qsum += alen
        for j, b in enumerate(spadnames):
            blen = spadlen[b]
            expected[i, j] = all_dots * alen * blen * 1. / S

    assert int(round(expected.sum())) == all_dots

    # Calculate the statistical significance for each cell
    from scipy.stats.distributions import poisson
    M = m * n  # multiple testing
    logmp = np.zeros((m, n))
    for i in xrange(m):
        for j in xrange(n):
            obs, exp = observed[i, j], expected[i, j]
            pois = max(poisson.pmf(obs, exp), 1e-250)  # Underflow
            logmp[i, j] = max(- log(pois), 0)

    return logmp