/* BIFF2-4 single-sheet workbooks
7779
function write_biff_rec(ba, t, payload, length) {
	var len = (length || (payload||[]).length);
	var o = ba.next(4 + len);
	o.write_shift(2, t);
	o.write_shift(2, len);
	if(len > 0 && is_buf(payload)) ba.push(payload);
}
882641
function write_BIFF2LABEL(r/*:number*/, c/*:number*/, val) {
	var out = new_buf(8 + 2*val.length);
	write_BIFF2Cell(out, r, c);
	out.write_shift(1, val.length);
	out.write_shift(val.length, val, 'sbcs');
	return out.l < out.length ? out.slice(0, out.l) : out;
}
1104454
def detect_worksheets(archive):
    """"""
    # content types has a list of paths but no titles
    # workbook has a list of titles and relIds but no paths
    # workbook_rels has a list of relIds and paths but no titles
    # rels = {'id':{'title':'', 'path':''} }
    content_types = read_content_types(archive)
    valid_sheets = dict((path, ct) for ct, path in content_types if ct == WORKSHEET_TYPE)
    rels = dict(read_rels(archive))
    for sheet in read_sheets(archive):
        rel = rels[sheet['id']]
        rel['title'] = sheet['name']
        rel['sheet_id'] = sheet['sheetId']
        rel['state'] = sheet.get('state', 'visible')
        if ("/" + rel['path'] in valid_sheets
            or "worksheets" in rel['path']): # fallback in case content type is missing
            yield rel
793828
function write_ws_biff8(idx, opts, wb) {
	var ba = buf_array();
	var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
	var _WB = ((wb||{}).Workbook||{});
	var _sheet = ((_WB.Sheets||[])[idx]||{});
	var dense = Array.isArray(ws);
	var b8 = opts.biff == 8;
	var ref, rr = "", cols = [];
	var range = safe_decode_range(ws['!ref'] || "A1");
	var MAX_ROWS = b8 ? 65536 : 16384;
	if(range.e.c > 0xFF || range.e.r >= MAX_ROWS) {
		if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
		range.e.c = Math.min(range.e.c, 0xFF);
		range.e.r = Math.min(range.e.c, MAX_ROWS-1);
	}

	write_biff_rec(ba, 0x0809, write_BOF(wb, 0x10, opts));
	/* ... */
	write_biff_rec(ba, "CalcMode", writeuint16(1));
	write_biff_rec(ba, "CalcCount", writeuint16(100));
	write_biff_rec(ba, "CalcRefMode", writebool(true));
	write_biff_rec(ba, "CalcIter", writebool(false));
	write_biff_rec(ba, "CalcDelta", write_Xnum(0.001));
	write_biff_rec(ba, "CalcSaveRecalc", writebool(true));
	write_biff_rec(ba, "PrintRowCol", writebool(false));
	write_biff_rec(ba, "PrintGrid", writebool(false));
	write_biff_rec(ba, "GridSet", writeuint16(1));
	write_biff_rec(ba, "Guts", write_Guts([0,0]));
	/* ... */
	write_biff_rec(ba, "HCenter", writebool(false));
	write_biff_rec(ba, "VCenter", writebool(false));
	/* ... */
	write_biff_rec(ba, 0x200, write_Dimensions(range, opts));
	/* ... */

	if(b8) ws['!links'] = [];
	for(var R = range.s.r; R <= range.e.r; ++R) {
		rr = encode_row(R);
		for(var C = range.s.c; C <= range.e.c; ++C) {
			if(R === range.s.r) cols[C] = encode_col(C);
			ref = cols[C] + rr;
			var cell = dense ? (ws[R]||[])[C] : ws[ref];
			if(!cell) continue;
			/* write cell */
			write_ws_biff8_cell(ba, cell, R, C, opts);
			if(b8 && cell.l) ws['!links'].push([ref, cell.l]);
		}
	}
	var cname = _sheet.CodeName || _sheet.name || s;
	/* ... */
	if(b8 && _WB.Views) write_biff_rec(ba, "Window2", write_Window2(_WB.Views[0]));
	/* ... */
	if(b8 && (ws['!merges']||[]).length) write_biff_rec(ba, "MergeCells", write_MergeCells(ws['!merges']));
	/* ... */
	if(b8) write_ws_biff8_hlinks(ba, ws);
	/* ... */
	write_biff_rec(ba, "CodeName", write_XLUnicodeString(cname, opts));
	/* ... */
	if(b8) write_FEAT(ba, ws);
	/* ... */
	write_biff_rec(ba, "EOF");
	return ba.end();
}
645086
def sheets(self):
        """"""
        data = Dict()
        for src in [src for src in self.zipfile.namelist() if 'xl/worksheets/' in src]:
            name = os.path.splitext(os.path.basename(src))[0]
            xml = self.xml(src)
            data[name] = xml
        return data
1200710
File appendSheet(final List<WorksheetContent> worksheetContents) throws IOException {
        final ImmutableSet<String> worksheetNames = FluentIterable.from(worksheetContents)
                .transform(new Function<WorksheetContent, String>() {
                    @Nullable @Override public String apply(@Nullable final WorksheetContent worksheetContent) {
                        return worksheetContent.getSpec().getSheetName();
                    }
                }).toSet();
        if(worksheetNames.size() < worksheetContents.size()) {
            throw new IllegalArgumentException("Sheet names must have distinct names");
        }
        for (final String worksheetName : worksheetNames) {
            if(worksheetName.length() > 30) {
                throw new IllegalArgumentException(
                        String.format("Sheet name cannot exceed 30 characters (invalid name: '%s')",
                                worksheetName));
            }
        }

        final XSSFWorkbook workbook = new XSSFWorkbook();
        final File tempFile =
                File.createTempFile(ExcelConverter.class.getName(), UUID.randomUUID().toString() + XLSX_SUFFIX);
        final FileOutputStream fos = new FileOutputStream(tempFile);

        for (WorksheetContent worksheetContent : worksheetContents) {
            final WorksheetSpec spec = worksheetContent.getSpec();
            appendSheet(workbook, worksheetContent.getDomainObjects(), spec.getFactory(), spec.getSheetName());
        }
        workbook.write(fos);
        fos.close();
        return tempFile;
    }
547453
function doExport() {
		/*
			If opts is array of arrays then this is a
			multisheet workboook, else it is a singlesheet
		*/
		if (typeof opts == 'object' && Array.isArray(opts)) {
			if (data && data.length > 0) {
				data.forEach(function(dat, idx) {
					prepareSheet(opts[idx], dat, undefined, idx + 1);
				});
			}
		} else {
			prepareSheet(opts, data, columns, 1);
		}

		saveWorkbook(cb);
	}
1103470
def add_worksheet(self):
        """"""
        wsh = self.workbook.add_worksheet()
        if self.vars.fld2col_widths is not None:
            self.set_xlsx_colwidths(wsh, self.vars.fld2col_widths, self.wbfmtobj.get_prt_flds())
        return wsh
302377
function parse_PtgSheet(blob, length, opts) {
	blob.l += 5;
	blob.l += 2;
	blob.l += (opts.biff == 2 ? 1 : 4);
	return ["PTGSHEET"];
}
712907
def workbook_data(self):
        """"""
        document = XML(
            fn=os.path.splitext(self.fn)[0]+'.xml', 
            root=Element.workbook())
        shared_strings = [
            str(t.text) for t in 
            self.xml('xl/sharedStrings.xml')
                .root.xpath(".//xl:t", namespaces=self.NS)]
        for key in self.sheets.keys():
            worksheet = self.sheets[key].transform(XT, shared_strings=shared_strings)
            document.root.append(worksheet.root)
        return document
368515
function parse_ExternSheet(blob, length, opts) {
	if(opts.biff < 8) return parse_ShortXLUnicodeString(blob, length, opts);
	var o = [], target = blob.l + length, len = blob.read_shift(2);
	while(len-- !== 0) o.push(parse_XTI(blob, 6));
		// [iSupBook, itabFirst, itabLast];
	var oo = [];
	return o;
}
404481
def single_cell ref
      if ref.sheet_name.nil?
        raise 'cell references at the workbook level must include a sheet reference (eg. Sheet1!A1)'
      else
        worksheets[ref.sheet_name][ref.row][ref.col]
      end
    end
1310379
function _storeBoundsheet($sheetname,$offset)
    {
        $record    = 0x0085;                    // Record identifier
        if ($this->_BIFF_version == 0x0600) {
            $length    = 0x08 + strlen($sheetname); // Number of bytes to follow
        } else {
            $length = 0x07 + strlen($sheetname); // Number of bytes to follow
        }

        $grbit     = 0x0000;                    // Visibility and sheet type
        $cch       = strlen($sheetname);        // Length of sheet name

        $header    = pack("vv",  $record, $length);
        if ($this->_BIFF_version == 0x0600) {
            $data      = pack("Vvv", $offset, $grbit, $cch);
        } else {
            $data      = pack("VvC", $offset, $grbit, $cch);
        }
        $this->_append($header.$data.$sheetname);
    }
690477
function _storeWorkbook()
    {
        if (count($this->_worksheets) == 0) {
            return true;
        }

        // Ensure that at least one worksheet has been selected.
        if ($this->_activesheet == 0) {
            $this->_worksheets[0]->selected = 1;
        }

        // Calculate the number of selected worksheet tabs and call the finalization
        // methods for each worksheet
        $total_worksheets = count($this->_worksheets);
        for ($i = 0; $i < $total_worksheets; $i++) {
            if ($this->_worksheets[$i]->selected) {
                $this->_selected++;
            }
            $this->_worksheets[$i]->close($this->_sheetnames);
        }

        // Add Workbook globals
        $this->_storeBof(0x0005);
        $this->_storeCodepage();
        if ($this->_BIFF_version == 0x0600) {
            $this->_storeWindow1();
        }
        if ($this->_BIFF_version == 0x0500) {
            $this->_storeExterns();    // For print area and repeat rows
        }
        $this->_storeNames();      // For print area and repeat rows
        if ($this->_BIFF_version == 0x0500) {
            $this->_storeWindow1();
        }
        $this->_storeDatemode();
        $this->_storeAllFonts();
        $this->_storeAllNumFormats();
        $this->_storeAllXfs();
        $this->_storeAllStyles();
        $this->_storePalette();
        $this->_calcSheetOffsets();

        // Add BOUNDSHEET records
        for ($i = 0; $i < $total_worksheets; $i++) {
            $this->_storeBoundsheet($this->_worksheets[$i]->name,$this->_worksheets[$i]->offset);
        }

        if ($this->_country_code != -1) {
            $this->_storeCountry();
        }

        if ($this->_BIFF_version == 0x0600) {
            //$this->_storeSupbookInternal();
            /* TODO: store external SUPBOOK records and XCT and CRN records
            in case of external references for BIFF8 */
            //$this->_storeExternsheetBiff8();
            $this->_storeSharedStringsTable();
        }

        // End Workbook globals
        $this->_storeEof();

        // Store the workbook in an OLE container
        $res = $this->_storeOLEFile();
        if ($this->isError($res)) {
            return $this->raiseError($res->getMessage());
        }
        return true;
    }
815878
function parse_BrtFmlaBool(data, length, opts) {
	var end = data.l + length;
	var cell = parse_XLSBCell(data);
	cell.r = opts['!row'];
	var value = data.read_shift(1);
	var o = [cell, value, 'b'];
	if(opts.cellFormula) {
		data.l += 2;
		var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
		o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
	}
	else data.l = end;
	return o;
}
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)
135341
function Spreadsheet_Excel_Writer_BIFFwriter()
    {
        $this->_byte_order = '';
        $this->_data       = '';
        $this->_datasize   = 0;
        $this->_limit      = 2080;
        $this->_tmp_dir    = '';
        // Set the byte order
        $this->_setByteOrder();
    }