Worksheet requirements Operate as sheet inside workbook or standalone Load and Save from file and stream Access/Add/Delete individual cells Manage column widths and row heights
511584
function(options) {
  options = options || {};

  // in a workbook, each sheet will have a number
  this.id = options.id;
  this.orderNo = options.orderNo;

  // and a name
  this.name = options.name || `Sheet${this.id}`;

  // add a state
  this.state = options.state || 'visible';

  // rows allows access organised by row. Sparse array of arrays indexed by row-1, col
  // Note: _rows is zero based. Must subtract 1 to go from cell.row to index
  this._rows = [];

  // column definitions
  this._columns = null;

  // column keys (addRow convenience): key ==> this._collumns index
  this._keys = {};

  // keep record of all merges
  this._merges = {};

  // record of all row and column pageBreaks
  this.rowBreaks = [];

  this._workbook = options.workbook;

  // for tabColor, default row height, outline levels, etc
  this.properties = Object.assign(
    {},
    {
      defaultRowHeight: 15,
      dyDescent: 55,
      outlineLevelCol: 0,
      outlineLevelRow: 0,
    },
    options.properties
  );

  // for all things printing
  this.pageSetup = Object.assign(
    {},
    {
      margins: { left: 0.7, right: 0.7, top: 0.75, bottom: 0.75, header: 0.3, footer: 0.3 },
      orientation: 'portrait',
      horizontalDpi: 4294967295,
      verticalDpi: 4294967295,
      fitToPage: !!(options.pageSetup && ((options.pageSetup.fitToWidth || options.pageSetup.fitToHeight) && !options.pageSetup.scale)),
      pageOrder: 'downThenOver',
      blackAndWhite: false,
      draft: false,
      cellComments: 'None',
      errors: 'displayed',
      scale: 100,
      fitToWidth: 1,
      fitToHeight: 1,
      paperSize: undefined,
      showRowColHeaders: false,
      showGridLines: false,
      firstPageNumber: undefined,
      horizontalCentered: false,
      verticalCentered: false,
      rowBreaks: null,
      colBreaks: null,
    },
    options.pageSetup
  );

  this.dataValidations = new DataValidations();

  // for freezepanes, split, zoom, gridlines, etc
  this.views = options.views || [];

  this.autoFilter = options.autoFilter || null;

  // for images, etc
  this._media = [];
}
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)
694155
def create_or_open_sheet_at index
      s = self[index]
      s = self[index] = Workbook::Sheet.new if s == nil
      s.book = self
      s
    end
945930
def adjust_column_width(worksheet):
    
    dims = {}
    padding = 1
    for row in worksheet.rows:
        for cell in row:
            if not cell.value:
                continue
            dims[cell.column] = max(
                dims.get(cell.column, 0),
                len(str(cell.value))
            )
    for col, value in list(dims.items()):
        worksheet.column_dimensions[col].width = value + padding
529354
function worksheetData(worksheet) {
    return {
        worksheetId: getItemIdFromUrl(g(worksheet.id)),
        title: g(worksheet.title),
        updated: g(worksheet.updated),
        colCount: g(worksheet['gs$colCount']),
        rowCount: g(worksheet['gs$rowCount'])
    };
}
1343039
def _shape2xls(self, worksheets):
        

        __, __, tabs = self.code_array.shape

        if tabs > self.xls_max_tabs:
            tabs = self.xls_max_tabs

        for tab in xrange(tabs):
            worksheet = self.workbook.add_sheet(str(tab))
            worksheets.append(worksheet)
779384
def push(self, vs):
        ''
        if vs:
            vs.vd = self
            if vs in self.sheets:
                self.sheets.remove(vs)
                self.sheets.insert(0, vs)
            elif not vs.loaded:
                self.sheets.insert(0, vs)
                vs.reload()
                vs.recalc()  # set up Columns
            else:
                self.sheets.insert(0, vs)

            if vs.precious and vs not in vs.vd.allSheets:
                vs.vd.allSheets[vs] = vs.name
            return vs
362745
function sheetToTable(sheet) {
  if (sheet.data.length === 0 || sheet.data[0].rowData === undefined) {
    return {
      title: sheet.properties.title,
      headers: [],
      formats: [],
      rows: []
    };
  }
  const gridData = sheet.data[0]; // first (unique) range
  const headers = gridData.rowData[0].values // first row (headers)
    .map(col => formattedValue(col));

  const otherRows = gridData.rowData.slice(1);

  const values =
    otherRows.length > 0
      ? otherRows[0].values
      : new Array(headers.length).fill({});

  return {
    title: sheet.properties.title,
    headers: headers,
    formats: values.map(value => effectiveFormat(value)),
    rows: otherRows.map(row =>
      zipObject(
        headers,
        row.values.map(value => ({
          value: effectiveValue(value),
          stringValue: formattedValue(value)
        }))
      )
    )
  };
}
567045
def workbook_to_reader(xlwt_wb):
    
    _xlrd_required()
    fh = BytesIO()
    xlwt_wb.save(fh)
    # prep for reading
    fh.seek(0)
    return xlrd.open_workbook(file_contents=fh.read())
47077
static Workbook toWorkbook(final IDataSet dataSet, final Workbook formatting) {
        Workbook result = formatting == null ? ConverterUtils.newWorkbook() : ConverterUtils.clearContent(formatting);
        
        Sheet sheet = result.createSheet(dataSet.getName());
        for (IDsRow row : dataSet) {
            Row wbRow = sheet.createRow(row.index() - 1);
            for (IDsCell cell : row) {
                Cell wbCell = wbRow.createCell(cell.index() - 1);
                ConverterUtils.populateCellValue(wbCell, cell.getValue());
            }
        }
        
        return result;        
    }
481749
def main():
  """"""
  parser = argparse.ArgumentParser(
      description='Reads in a .xls file and generates a units module for '
                  'OpenHTF.',
      prog='python units_from_xls.py')
  parser.add_argument('xlsfile', type=str,
                      help='the .xls file to parse')
  parser.add_argument(
      '--outfile',
      type=str,
      default=os.path.join(os.path.dirname(__file__), os.path.pardir,
                           'openhtf','util', 'units.py'),
      help='where to put the generated .py file.')
  args = parser.parse_args()

  if not os.path.exists(args.xlsfile):
    print('Unable to locate the file "%s".' % args.xlsfile)
    parser.print_help()
    sys.exit()

  unit_defs = unit_defs_from_sheet(
      xlrd.open_workbook(args.xlsfile).sheet_by_name(SHEET_NAME),
      COLUMN_NAMES)

  _, tmp_path = mkstemp()
  with open(tmp_path, 'w') as new_file:
    new_file.write(PRE)
    new_file.writelines(
        [line.encode('utf8', 'replace') for line in unit_defs])
    new_file.write(POST)
    new_file.flush()

  os.remove(args.outfile)
  shutil.move(tmp_path, args.outfile)
800686
def export_to_xlsx(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
    """"""

    workbook = Workbook()
    sheet = workbook.active
    sheet.title = sheet_name
    prepared_table = prepare_to_export(table, *args, **kwargs)

    # Write header
    field_names = next(prepared_table)
    for col_index, field_name in enumerate(field_names):
        cell = sheet.cell(row=1, column=col_index + 1)
        cell.value = field_name

    # Write sheet rows
    _convert_row = _python_to_cell(list(map(table.fields.get, field_names)))
    for row_index, row in enumerate(prepared_table, start=1):
        for col_index, (value, number_format) in enumerate(_convert_row(row)):
            cell = sheet.cell(row=row_index + 1, column=col_index + 1)
            cell.value = value
            if number_format is not None:
                cell.number_format = number_format

    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="xlsx")
    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
469158
def create_excel_workbook(data, result_info_key, identifier_keys):
    """"""
    workbook = analytics_data_excel.get_excel_workbook(data, result_info_key, identifier_keys)
    adjust_column_width_workbook(workbook)
    return workbook
517582
function saveWorkbook(cb) {
		//console.log(wb);
		var XLSX;

		if (typeof filename == 'undefined') {
			res = wb;
		} else {
			XLSX = getXLSX();

			if (utils.isNode || utils.isMeteorServer) {
				XLSX.writeFile(wb, filename);
			} else {
				var wopts = {bookType: 'xlsx', bookSST: false, type: 'binary'};
				var wbout = XLSX.write(wb, wopts);

				function s2ab(s) {
					var buf = new ArrayBuffer(s.length);
					var view = new Uint8Array(buf);
					for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
					return buf;
				}

				/* the saveAs call downloads a file on the local machine */
				//				saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), '"'+filename+'"')
				//				saveAs(new Blob([s2ab(wbout)],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}), filename)
				//				saveAs(new Blob([s2ab(wbout)],{type:"application/vnd.ms-excel"}), '"'+filename+'"');
				if (isIE() == 9) {
					throw new Error(
						'Cannot save XLSX files in IE9. Please use XLS() export function'
					);
					//					var URI = 'data:text/plain;charset=utf-8,';

					/** @todo Check if this code is required */

					/*/*
					var testlink = window.open("about:blank", "_blank");
					var s = '';
					for(var i=0,ilen=wbout.length;i<ilen;i++) {
						var ch = wbout.charCodeAt(i);
						if(i<20) console.log('&#'+ch+';');
						s += '&#x'+ch.toString(16)+';';
					};
					testlink.document.write(s); //fileData has contents for the file
					testlink.document.close();
					testlink.document.execCommand('SaveAs', false, filename);
					testlink.close();
*/
					//					alert('ie9');
				} else {
					saveAs(new Blob([s2ab(wbout)], {type: 'application/octet-stream'}), filename);
				}
			}
		}
		/*/*
		// data.forEach(function(d){
		// 	s += columns.map(function(col){
		// 		return d[col.columnid];
		// 	}).join(opts.separator)+'\n';
		// });
		// alasql.utils.saveFile(filename,s);
*/
	}
7319
def importConnFromExcel (fileName, sheetName):
    ''' '''
    import openpyxl as xl

    # set columns
    colPreTags = 0 # 'A'
    colPostTags = 1 # 'B'
    colConnFunc = 2 # 'C'
    colSyn = 3 # 'D'
    colProb = 5 # 'F'
    colWeight = 6 # 'G'
    colAnnot = 8 # 'I' 

    outFileName = fileName[:-5]+'_'+sheetName+'.py' # set output file name

    connText = """## Generated using importConnFromExcel() function in params/utils.py \n\nnetParams['connParams'] = [] \n\n"""
    
    # open excel file and sheet
    wb = xl.load_workbook(fileName)
    sheet = wb.get_sheet_by_name(sheetName)
    numRows = sheet.get_highest_row()

    with open(outFileName, 'w') as f:
        f.write(connText)  # write starting text
        for row in range(1,numRows+1):
            if sheet.cell(row=row, column=colProb).value:  # if not empty row
                print('Creating conn rule for row ' + str(row))
                # read row values
                pre = sheet.cell(row=row, column=colPreTags).value
                post = sheet.cell(row=row, column=colPostTags).value
                func = sheet.cell(row=row, column=colConnFunc).value
                syn = sheet.cell(row=row, column=colSyn).value
                prob = sheet.cell(row=row, column=colProb).value
                weight = sheet.cell(row=row, column=colWeight).value

                # write preTags
                line = "netParams['connParams'].append({'preConds': {"
                for i,cond in enumerate(pre.split(';')):  # split into different conditions
                    if i>0: line = line + ", "
                    cond2 = cond.split('=')  # split into key and value
                    line = line + "'" + cond2[0].replace(' ','') + "': " + cond2[1].replace(' ','')   # generate line
                line = line + "}" # end of preTags      

                # write postTags
                line = line + ",\n'postConds': {"
                for i,cond in enumerate(post.split(';')):  # split into different conditions
                    if i>0: line = line + ", "
                    cond2 = cond.split('=')  # split into key and value
                    line = line + "'" + cond2[0].replace(' ','') + "': " + cond2[1].replace(' ','')   # generate line
                line = line + "}" # end of postTags         
                line = line + ",\n'connFunc': '" + func + "'"  # write connFunc
                line = line + ",\n'synMech': '" + syn + "'"  # write synReceptor
                line = line + ",\n'probability': " + str(prob)  # write prob
                line = line + ",\n'weight': " + str(weight)  # write prob
                line = line + "})"  # add closing brackets
                line = line + '\n\n' # new line after each conn rule
                f.write(line)
871184
def create_or_open_table_at index
      t = self[index]
      t = self[index] = Workbook::Table.new if t == nil
      t.sheet = self
      t
    end
1302495
def json2excel(items, keys, filename, page_size=60000):
    
    wb = xlwt.Workbook()
    rowindex = 0
    sheetindex = 0
    for item in items:
        if rowindex % page_size == 0:
            sheetname = "%02d" % sheetindex
            ws = wb.add_sheet(sheetname)
            rowindex = 0
            sheetindex += 1

            colindex = 0
            for key in keys:
                ws.write(rowindex, colindex, key)
                colindex += 1
            rowindex += 1

        colindex = 0
        for key in keys:
            v = item.get(key, "")
            if type(v) == list:
                v = ','.join(v)
            if type(v) == set:
                v = ','.join(v)
            ws.write(rowindex, colindex, v)
            colindex += 1
        rowindex += 1

    logging.debug(filename)
    wb.save(filename)