How to use the openpyxl.reader.excel.load_workbook function in openpyxl

To help you get started, we’ve selected a few openpyxl examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github raxcat / ExcelToStrings_ObjC / translate.py View on Github external
#check if running with python3
if sys.version_info[0] < 3:
    raise "Must be using Python 3"

# print ('Number of arguments:', len(sys.argv), 'arguments.')
# print ('Argument List:', str(sys.argv))

if len(sys.argv) < 2 :
    print('Error: No input')
    sys.exit(0)

#load excel file
filename = sys.argv[1]
wb = load_workbook(filename = filename)
sheet = wb.active 

englishColumnIndex = 'A'
if len(sys.argv) > 2 :
    englishColumnIndex = sys.argv[2]
print('English column index:' + englishColumnIndex)

ignore_row_number = 0
if len(sys.argv) > 3:
    ignore_row_number = int(sys.argv[3])
print('ignore_row_number:' + str(ignore_row_number))

ignore_column_number = 0
if len(sys.argv) > 4:
    ignore_column_number = int(sys.argv[4])
print('ignore_column_number:' + str(ignore_column_number))
github psychopy / psychopy / psychopy / data.py View on Github external
except:
            raise ImportError('Could not open %s as conditions' % fileName)
        f.close()
        trialList = []
        fieldNames = trialsArr[0] # header line first
        _assertValidVarNames(fieldNames, fileName)
        for row in trialsArr[1:]:
            thisTrial = {}
            for fieldN, fieldName in enumerate(fieldNames):
                thisTrial[fieldName] = row[fieldN] # type is correct, being .pkl
            trialList.append(thisTrial)
    else:
        if not haveOpenpyxl:
            raise ImportError('openpyxl is required for loading excel format files, but it was not found.')
        try:
            wb = load_workbook(filename=fileName)
        except: # InvalidFileException(unicode(e)): # this fails
            raise ImportError('Could not open %s as conditions' % fileName)
        ws = wb.worksheets[0]
        nCols = ws.get_highest_column()
        nRows = ws.get_highest_row()

        #get parameter names from the first row header
        fieldNames = []
        for colN in range(nCols):
            fieldName = ws.cell(_getExcelCellName(col=colN, row=0)).value
            fieldNames.append(fieldName)
        _assertValidVarNames(fieldNames, fileName)

        #loop trialTypes
        trialList = []
        for rowN in range(1, nRows):#skip header first row
github nprapps / dailygraphics / copytext.py View on Github external
def load(self):
        """
        Parses the downloaded .xlsx file and writes it as JSON.
        """
        try:
            book = load_workbook(self._filename, data_only=True)
        except IOError:
            raise CopyException('"%s" does not exist. Have you run "fab update_copy"?' % self._filename)

        for sheet in book:
            columns = []
            rows = []

            for i, row in enumerate(sheet.rows):
                row_data = [c.internal_value for c in row]

                if i == 0:
                    columns = row_data 
                    continue

                # If nothing in a row then it doesn't matter
                if all([c is None for c in row_data]):
github jazzband / tablib / src / tablib / formats / _xlsx.py View on Github external
def detect(cls, stream):
        """Returns True if given stream is a readable excel file."""
        if isinstance(stream, bytes):
            # load_workbook expects a file-like object.
            stream = BytesIO(stream)
        try:
            openpyxl.reader.excel.load_workbook(stream, read_only=True)
            return True
        except Exception:
            return False
github jazzband / tablib / src / tablib / formats / _xlsx.py View on Github external
def import_set(cls, dset, in_stream, headers=True):
        """Returns databook from XLS stream."""

        dset.wipe()

        xls_book = openpyxl.reader.excel.load_workbook(BytesIO(in_stream), read_only=True)
        sheet = xls_book.active

        dset.title = sheet.title

        for i, row in enumerate(sheet.rows):
            row_vals = [c.value for c in row]
            if (i == 0) and (headers):
                dset.headers = row_vals
            else:
                dset.append(row_vals)
github jazzband / tablib / src / tablib / formats / _xlsx.py View on Github external
def import_book(cls, dbook, in_stream, headers=True):
        """Returns databook from XLS stream."""

        dbook.wipe()

        xls_book = openpyxl.reader.excel.load_workbook(BytesIO(in_stream), read_only=True)

        for sheet in xls_book.worksheets:
            data = tablib.Dataset()
            data.title = sheet.title

            for i, row in enumerate(sheet.rows):
                row_vals = [c.value for c in row]
                if (i == 0) and (headers):
                    data.headers = row_vals
                else:
                    data.append(row_vals)

            dbook.add_sheet(data)
github JackPotte / JackBot / subster.py View on Github external
def xlsx2csv(self, external_buffer, sheet):
        """Convert xlsx (EXCEL) data to csv format.
        """

        wb = openpyxl.reader.excel.load_workbook(StringIO.StringIO(external_buffer), use_iterators = True)

        sheet_ranges = wb.get_sheet_by_name(name = sheet)

        output = StringIO.StringIO()
        spamWriter = csv.writer(output)

        for row in sheet_ranges.iter_rows(): # it brings a new method: iter_rows()
            spamWriter.writerow([ cell.internal_value for cell in row ])

        external_buffer = output.getvalue()
        output.close()

        return external_buffer
github bukun / TorCMS / torcms / script / script_gen_category.py View on Github external
def gen_xlsx_category():
    '''
    Genereting catetory from xlsx file.
    '''
    if os.path.exists(XLSX_FILE):
        pass
    else:
        return
    # 在分类中排序
    order_index = 1

    all_cate_arr = []

    for sheet_ranges in load_workbook(filename=XLSX_FILE):
        kind_sig = str(sheet_ranges['A1'].value).strip()

        for row_num in range(3, 10000):

            # 父类
            a_cell_val = sheet_ranges['A{0}'.format(row_num)].value
            b_cell_val = sheet_ranges['B{0}'.format(row_num)].value
            c_cell_val = sheet_ranges['C{0}'.format(row_num)].value


            if a_cell_val or b_cell_val or c_cell_val:
                pass
            else:
                break

            if a_cell_val and a_cell_val != '':
github dimagi / dimagi-utils / dimagi / utils / excel.py View on Github external
def __init__(self, f):
        if isinstance(f, basestring):
            filename = f
        elif not isinstance(f, file):
            tmp = NamedTemporaryFile(mode='wb', suffix='xlsx', delete=False)
            filename = tmp.name
            tmp.write(f.read())
            tmp.close()
        else:
            filename = f

        self.wb = openpyxl.reader.excel.load_workbook(filename, use_iterators=True)
        self.worksheets_by_title = {}
        self.worksheets = []
        for worksheet in self.wb.worksheets:
            ws = WorksheetJSONReader(worksheet)
            self.worksheets_by_title[worksheet.title] = ws
            self.worksheets.append(ws)
github nprapps / copytext / copytext.py View on Github external
def load(self):
        """
        Parses the downloaded Excel file.
        """
        try:
            book = load_workbook(self._filename, data_only=True)
        except IOError:
            raise CopyException(
                '"%s" does not exist. Have you run "fab update_copy"?'
                % self._filename
            )

        for sheet in book:
            columns = []
            rows = []

            for i, row in enumerate(sheet.rows):
                if i == 0:
                    for c in row:
                        d = c.internal_value

                        # Columns cease once an empty header is found