convert xlwt Workbook instance to an xlrd instance for reading
777423
def xlsx_to_reader(xlsx_wb):
    
    fh = xlsx_to_strio(xlsx_wb)
    return xlrd.open_workbook(file_contents=fh.read())
132548
public static XlsWorkbook getWorkbook(File file) throws IOException
    {
        try
        {
            return new XlsWorkbook(file);
        }
        catch(jxl.read.biff.BiffException e)
        {
            throw new IOException(e);
        }
    }
211389
public static Workbook getWorkbook(File file) throws IOException
    {
        Workbook ret = null;
        String lowerFilename = file.getName().toLowerCase();
        if(lowerFilename.endsWith("."+CommonFiles.XLS_EXT))
        {
            ret = XlsWorkbook.getWorkbook(file);
        }
        else if(lowerFilename.endsWith("."+CommonFiles.XLSX_EXT))
        {
            XlsxWorkbook.initJaxbContexts();
            ret = XlsxWorkbook.getWorkbook(file);
        }
        return ret;
    }
1342513
def convert(input_file_name, **kwargs):
    """"""
    delimiter = kwargs["delimiter"] or ","
    quotechar = kwargs["quotechar"] or "|"

    if six.PY2:
        delimiter = delimiter.encode("utf-8")
        quotechar = quotechar.encode("utf-8")

    # Read CSV and form a header and rows list
    with open(input_file_name, "rb") as input_file:
        reader = csv.reader(input_file,
                            encoding="utf-8",
                            delimiter=delimiter,
                            quotechar=quotechar)

        csv_headers = []
        if not kwargs.get("no_header"):
            # Read header from first line
            csv_headers = next(reader)

        csv_rows = [row for row in reader if row]

        # Set default column name if header is not present
        if not csv_headers and len(csv_rows) > 0:
            end = len(csv_rows[0]) + 1
            csv_headers = ["Column {}".format(n) for n in range(1, end)]

    # Render csv to HTML
    html = render_template(csv_headers, csv_rows, **kwargs)

    # Freeze all JS files in template
    return freeze_js(html)
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
150928
def toxlsx(tbl, filename, sheet=None, encoding=None):
    

    import openpyxl
    if encoding is None:
        encoding = locale.getpreferredencoding()
    wb = openpyxl.Workbook(write_only=True)
    ws = wb.create_sheet(title=sheet)
    for row in tbl:
        ws.append(row)
    wb.save(filename)
917509
def process_xlsx(content):
    
    data = {}
    workbook = xlrd.open_workbook(file_contents=content)
    worksheets = [w for w in workbook.sheet_names() if not w.startswith('_')]
    for worksheet_name in worksheets:
        if worksheet_name.startswith('_'):
            continue

        worksheet = workbook.sheet_by_name(worksheet_name)

        merged_cells = worksheet.merged_cells
        if len(merged_cells):
            raise MergedCellError(worksheet.name, merged_cells)

        worksheet.name = slughifi(worksheet.name)
        headers = make_headers(worksheet)
        worksheet_data = make_worksheet_data(headers, worksheet)
        data[worksheet.name] = worksheet_data
    return data
1213272
def excel_to_bytes(wb: Workbook) -> bytes:
    
    memfile = io.BytesIO()
    wb.save(memfile)
    return memfile.getvalue()
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
79136
def _convert_to_style(cls, style_dict, num_format_str=None):
        
        import xlwt

        if style_dict:
            xlwt_stylestr = cls._style_to_xlwt(style_dict)
            style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
        else:
            style = xlwt.XFStyle()
        if num_format_str is not None:
            style.num_format_str = num_format_str

        return style
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)
80597
def wr_xlsx(self, fout_xlsx):
        """"""
        objwr = WrXlsxSortedGos("GOEA", self.sortobj)
        #### fld2fmt['ratio_in_study'] = '{:>8}'
        #### fld2fmt['ratio_in_pop'] = '{:>12}'
        #### ntfld2wbfmtdict = {
        # ntfld_wbfmt = {
        #     'ratio_in_study': {'align':'right'},
        #     'ratio_in_pop':{'align':'right'}}
        kws_xlsx = {
            'title': self.ver_list,
            'fld2fmt': {f:'{:8.2e}' for f in self.flds_cur if f[:2] == 'p_'},
            #'ntfld_wbfmt': ntfld_wbfmt,
            #### 'ntval2wbfmtdict': ntval2wbfmtdict,
            #'hdrs': [],
            'prt_flds': self.flds_cur}
        objwr.wr_xlsx_nts(fout_xlsx, self.desc2nts, **kws_xlsx)
732989
public static void writeWorkBookToExcel(Workbook workbook, OutputStream os) throws WriteExcelException {
        try {
            workbook.write(os);
        } catch (IOException e) {
            throw new WriteExcelException(e.getMessage());
        }
    }
145380
def _load_data(data_file, data_type):
    """"""
    raw_data = data_file.read()
    if data_type is None:
        data_type = data_file.name.split('.')[-1]
    # Data list to process
    data = []
    # JSON type
    if data_type == 'json':
        data = json.loads(raw_data)
        return data
    # CSV type
    elif data_type == 'csv':
        csv_data = StringIO(raw_data)
        reader = csv.DictReader(csv_data, delimiter=',')
        for line in reader:
            data.append(line)
        return data
    elif data_type in ['xlsx', 'xlsm', 'xltx', 'xltm']:
        excel_data = StringIO(raw_data)
        wb = openpyxl.load_workbook(excel_data)
        ws = wb.active
        # First headers
        headers = []
        for row in ws.iter_rows(max_row=1):
            for cell in row:
                tmp = '_'.join(cell.value.split(" ")).lower()
                headers.append(tmp)
        # Simulate DictReader
        for row in ws.iter_rows(row_offset=1):
            values = []
            for cell in row:
                values.append(cell.value)
            tmp = dict(itertools.izip(headers, values))
            if len(values) == len(headers) and not row_empty(values):
                data.append(tmp)
        return data
    # PO type
    elif data_type == 'po':
        po = polib.pofile(raw_data)
        for entry in po.untranslated_entries():
            data.append(entry.__dict__)
        return data
    # PROPERTIES type (used in Java and Firefox extensions)
    elif data_type == 'properties':
        lines = raw_data.split('\n')
        for l in lines:
            if l:
                var_id, string = l.split('=')
                tmp = dict(var_id=var_id, string=string)
                data.append(tmp)
        return data
    else:
        return data
1015722
def _read_xlsx_table(path):
    """"""
    workbook = pyxl.load_workbook(path)
    worksheet = workbook.active
    table = helpers.sheet_to_table(worksheet)

    return table
75074
def create_dataset(self, in_stream):
        
        assert XLS_IMPORT
        xls_book = xlrd.open_workbook(file_contents=in_stream)
        dataset = tablib.Dataset()
        sheet = xls_book.sheets()[0]

        dataset.headers = sheet.row_values(0)
        for i in range(1, sheet.nrows):
            dataset.append(sheet.row_values(i))
        return dataset
367907
function (formatter) {
    this.formatter = formatter;

    /**
     * Convert 
     *
     * @param filePath input ods file path
     */
    this.convert = function (filePath) {
        log('Message resource converter');
        log('Execute convert: ' + filePath);

        var excelApp = new ActiveXObject('Excel.Application');
        excelApp.Visible = true;
        log('Start');
        var book = excelApp.Workbooks.Open(filePath);
        var sheet = book.Worksheets(1);
        this.extractResources(sheet);
        log("End");
        book.Close(false);
        excelApp.Quit();
        excelApp = null;
    };

    this.data = [];
    this.fillData = function (sheet, lastCol, lastRow) {
      WScript.StdOut.Write('                        \r');
      this.data.push(undefined);
      for (var r = 1; r <= lastRow; r++) {
        var row = [];
        row.push(undefined);
        for (var c = 1; c <= lastCol; c++) {
          row.push(sheet.Cells(r, c).Value);
        }
        this.data.push(row);
        WScript.StdOut.Write('\rLoading... ' + r + ' / ' + lastRow);
      }
      WScript.StdOut.WriteLine();
    };
    this.value = function (row, col) {
        if (row >= this.data.length) throw Error('Array index out of range error(row): ' + row + ' in ' + this.data.length);
        if (col >= this.data[row].length) throw Error('Array index out of range error(col): ' + col + ' in ' + this.data[row].length);
        return this.data[row][col];
    };
    this.getLocaleColIndex = function(locale) {
        for (var col = 1; col < 100; col++) {
            if (this.value(3, col).toLowerCase() === locale.toLowerCase()) {
                return col;
            }
        }
        throw new Error('ref locale "' + locale + '" not found');
    };
    this.getRealValue = function (row, col) {
        var v = this.value(row, col);
        if (v === '^') {
            return this.getRealValue(row, col - 1);
        } else if (v === undefined) {
            return '';
        } else if (v.length > 1 && v.charAt(0) === '^') {
            var m = v.match(/^\^([a-z]+[\-_][a-zA-Z]+)$/);
            if (m) {
                var refLocaleCol = this.getLocaleColIndex(m[1]);
                return this.getRealValue(row, refLocaleCol);
            }
        }
        return v;
    };
    this.extractResources = function (sheet) {
        var locales = [];
        var lastLocaleCol = 1;
        var startLocaleCol = 4;
        for (var col = startLocaleCol, cellValue; cellValue = sheet.Cells(3, col).Value; col++) {
            lastLocaleCol = col;
        }
        var lastKeyRow = this.getLastKeyRow(sheet, 5);
        this.fillData(sheet, lastLocaleCol, lastKeyRow);
        console.log('Writing files...');
        var locales = [];
        for (var col = startLocaleCol; col <= lastLocaleCol; col++) {
            var localeKey = this.value(3, col);
            var lines = [];
            for (var row = 4; row <= lastKeyRow; row++) {
                var key = this.value(row, 3);
                var v = this.getRealValue(row, col);
                if (key) {
                    if (key.substr(0, 1) === '#') {
                        lines.push(formatter.formatComment(key));
                    } else {
                        if (row === lastKeyRow) {
                            lines.push(formatter.formatLastLine(key, v));
                        } else {
                            lines.push(formatter.formatLine(key, v));
                        }
                    }
                } else {
                    lines.push(''); // empty line
                }
            }
            locales.push(localeKey);
            this.writeSingleResourceFile(localeKey, formatter.normalizeLines(lines));
        }
        console.log('Wrote ' + locales.length + ' files in messages/ directory.');
    };
    this.writeSingleResourceFile = function (localeKey, lines) {
        var folderName = formatter.folderName;
        if (!fso.FolderExists(folderName)) {
            fso.CreateFolder(folderName);
        }
        // const
        var adTypeBinary = 1; // Binary
        var adTypeText = 2; // Text
        var adWriteChar = 0; // no EOL
        var adSaveCreateOverWrite = 2; // create or over write

        var filename = formatter.getFilePath(folderName, localeKey);
        var sw = new ActiveXObject('ADODB.Stream');
        sw.Type = adTypeText;
        sw.charset = 'utf-8';
        sw.Open();
        var headerText = formatter.formatHeader(localeKey);
        sw.WriteText(headerText, adWriteChar);
        for (var i = 0; i < lines.length; i++) {
            sw.WriteText(lines[i], adWriteChar);
        }
        var footerText = formatter.formatFooter(localeKey);
        sw.WriteText(footerText, adWriteChar);
        // Change to binary mode
        sw.Position = 0;
        sw.Type = adTypeBinary;
        // UTF-8 BOM
        if (outputBOM) {
            // Keep UTF-8 BOM
            sw.Position = 0;
        } else {
            // Skip UTF-8 BOM
            sw.Position = 3;
        }
        var binBlock = sw.Read();
        sw.Close();

        // Write binBlock as binary
        var os = new ActiveXObject('ADODB.Stream');
        os.Type = adTypeBinary;
        os.Open();
        os.Write(binBlock);
        os.SaveToFile(filename, adSaveCreateOverWrite);
        if (formatter.requireDefaultFile && formatter.isDefaultLocale(localeKey)) {
            var filenameOriginal = formatter.getDefaultFilePath(folderName);
            os.SaveToFile(filenameOriginal, adSaveCreateOverWrite);
        }
        os.Close();
    };

    // True if there are 
    this.getLastKeyRow = function (sheet, startRow) {
        var isBlank10rows = function (row) {
            for (var i = 0; i < 10; i++) {
                if (sheet.Cells(row + i, 3).Value) {
                    return false;
                }
            }
            return true;
        };
        for (var j = startRow; j < 5000; j++) { 
            if (isBlank10rows(j)) {
                return j - 1;
            }
        }
        return startRow;
    };
    return this;
}