kifield/kifield.py
def insert_part_fields_into_wb(part_fields_dict, wb, recurse=False):
    """Insert the fields in the extracted part dictionary into an XLSX workbook."""

    id_label = "Refs"

    # Get all the unique field labels used in the dictionary of part fields.
    field_labels = set([])
    for fields_and_values in part_fields_dict.values():
        for field_label in fields_and_values:
            field_labels.add(field_label)
    field_labels = sorted(field_labels)
    field_labels.insert(0, id_label)

    if wb is None:
        wb = pyxl.Workbook()  # No workbook given, so create one.

    wb = ungroup_wb(wb)  # Ungroup any grouped references.

    ws = wb.active  # Get the active sheet from the workbook.

    def set_cell_format(cell):
        """Set cell to TEXT format if it contains a string."""
        if cell.data_type == "s":
            cell.number_format = "@"

    if ws.min_column == ws.max_column:
        # If the given worksheet is empty, then create one using the part field labels.
        # Create header row with a column for each part field.
        for c, lbl in enumerate(field_labels, 1):
            cell = ws.cell(row=1, column=c)
            cell.value = lbl
            set_cell_format(cell)

        # Enter the part references into the part reference column.
        for row, ref in enumerate(sorted(part_fields_dict.keys()), 2):
            cell = ws.cell(row=row, column=1)
            cell.value = ref
            set_cell_format(cell)

    # Get the header row from the worksheet.
    header_row, headers = find_header(ws)
    header_labels = [cell.value for cell in headers]

    # Get column for each header field.
    header_columns = {h.value: h.column for h in headers}

    # Next open column. Combine with [0] in case there are no headers.
    next_header_column = max(list(header_columns.values()) + [0]) + 1

    # Find the column with the part references.
    ref_col, _ = find_header_column(headers, id_label)

    # Add all the missing part references from the field dictionary to the worksheet.
    # That will ensure a worksheet that only had a subset of the dictionary
    # part fields will get the missing ones.
    refs = set([])
    for row in range(header_row + 1, ws.max_row + 1):
        for ref in explode(ws.cell(row=row, column=ref_col).value):
            refs.add(ref)
    row = ws.max_row + 1
    for ref in sorted(part_fields_dict.keys()):
        if ref not in refs:
            cell = ws.cell(row=row, column=ref_col)
            cell.value = ref
            set_cell_format(cell)
            refs.add(ref)
            row += 1

    # Go through each row, see if any reference is in the part dictionary, and
    # insert/overwrite fields from the dictionary.
    for row in range(header_row + 1, ws.max_row + 1):
        for ref in explode(ws.cell(row=row, column=ref_col).value):
            try:
                fields = part_fields_dict[ref]
                for field, value in fields.items():
                    # Skip None fields.
                    if value is None:
                        continue

                    try:
                        # Match the field name to one of the headers and overwrite the
                        # cell value with the dictionary value.
                        header = lc_get_close_matches(field, header_labels, 1, 0.3)[0]
                        cell = ws.cell(row=row, column=header_columns[header])
                        logger.log(
                            DEBUG_OBSESSIVE,
                            "Updating {} field {} from {} to {}".format(
                                ref, field, cell.value, value
                            ),
                        )
                        cell.value = value
                        set_cell_format(cell)
                        logger.log(
                            DEBUG_OBSESSIVE,
                            "Type of {} field {} containing {} is {}".format(
                                ref, field, cell.value, cell.data_type
                            ),
                        )

                    except IndexError:
                        # The dictionary field didn't match any sheet header closely enough,
                        # so add a new column with the field name as the header label.
                        logger.log(
                            DEBUG_OBSESSIVE,
                            "Adding {} field {} with value {}".format(
                                ref, field, value
                            ),
                        )
                        cell = ws.cell(row=row, column=next_header_column)
                        cell.value = value
                        set_cell_format(cell)
                        new_header_cell = ws.cell(
                            row=header_row, column=next_header_column
                        )
                        new_header_cell.value = field
                        headers.append(new_header_cell)
                        header_labels.append(field)
                        header_columns[field] = next_header_column
                        next_header_column += 1

            except KeyError:
                pass  # The part reference doesn't exist in the dictionary.

    return wb
Insert the fields in the extracted part dictionary into an XLSX workbook.
Insert the fields in the extracted part dictionary into an XLSX workbook.
Insert the fields in the extracted part dictionary into an XLSX workbook .
def insert_part_fields_into_wb(part_fields_dict, wb, recurse=False):
    id_label = "Refs"
    field_labels = set([])
    for fields_and_values in part_fields_dict.values():
        for field_label in fields_and_values:
            field_labels.add(field_label)
    field_labels = sorted(field_labels)
    field_labels.insert(0, id_label)
    if wb is None:
        wb = pyxl.Workbook()  
    wb = ungroup_wb(wb)  
    ws = wb.active  
    def set_cell_format(cell):
        if cell.data_type == "s":
            cell.number_format = "@"
    if ws.min_column == ws.max_column:
        for c, lbl in enumerate(field_labels, 1):
            cell = ws.cell(row=1, column=c)
            cell.value = lbl
            set_cell_format(cell)
        for row, ref in enumerate(sorted(part_fields_dict.keys()), 2):
            cell = ws.cell(row=row, column=1)
            cell.value = ref
            set_cell_format(cell)
    header_row, headers = find_header(ws)
    header_labels = [cell.value for cell in headers]
    header_columns = {h.value: h.column for h in headers}
    next_header_column = max(list(header_columns.values()) + [0]) + 1
    ref_col, _ = find_header_column(headers, id_label)
    refs = set([])
    for row in range(header_row + 1, ws.max_row + 1):
        for ref in explode(ws.cell(row=row, column=ref_col).value):
            refs.add(ref)
    row = ws.max_row + 1
    for ref in sorted(part_fields_dict.keys()):
        if ref not in refs:
            cell = ws.cell(row=row, column=ref_col)
            cell.value = ref
            set_cell_format(cell)
            refs.add(ref)
            row += 1
    for row in range(header_row + 1, ws.max_row + 1):
        for ref in explode(ws.cell(row=row, column=ref_col).value):
            try:
                fields = part_fields_dict[ref]
                for field, value in fields.items():
                    if value is None:
                        continue
                    try:
                        header = lc_get_close_matches(field, header_labels, 1, 0.3)[0]
                        cell = ws.cell(row=row, column=header_columns[header])
                        logger.log(
                            DEBUG_OBSESSIVE,
                            "Updating {} field {} from {} to {}".format(
                                ref, field, cell.value, value
                            ),
                        )
                        cell.value = value
                        set_cell_format(cell)
                        logger.log(
                            DEBUG_OBSESSIVE,
                            "Type of {} field {} containing {} is {}".format(
                                ref, field, cell.value, cell.data_type
                            ),
                        )
                    except IndexError:
                        logger.log(
                            DEBUG_OBSESSIVE,
                            "Adding {} field {} with value {}".format(
                                ref, field, value
                            ),
                        )
                        cell = ws.cell(row=row, column=next_header_column)
                        cell.value = value
                        set_cell_format(cell)
                        new_header_cell = ws.cell(
                            row=header_row, column=next_header_column
                        )
                        new_header_cell.value = field
                        headers.append(new_header_cell)
                        header_labels.append(field)
                        header_columns[field] = next_header_column
                        next_header_column += 1
            except KeyError:
                pass  
    return wb
def insert_part_fields_into_wb ( part_fields_dict , wb , recurse = False ) : id_label = "Refs" field_labels = set ( [ ] ) for fields_and_values in part_fields_dict . values ( ) : for field_label in fields_and_values : field_labels . add ( field_label ) field_labels = sorted ( field_labels ) field_labels . insert ( 0 , id_label ) if wb is None : wb = pyxl . Workbook ( ) wb = ungroup_wb ( wb ) ws = wb . active def set_cell_format ( cell ) : """Set cell to TEXT format if it contains a string.""" if cell . data_type == "s" : cell . number_format = "@" if ws . min_column == ws . max_column : for c , lbl in enumerate ( field_labels , 1 ) : cell = ws . cell ( row = 1 , column = c ) cell . value = lbl set_cell_format ( cell ) for row , ref in enumerate ( sorted ( part_fields_dict . keys ( ) ) , 2 ) : cell = ws . cell ( row = row , column = 1 ) cell . value = ref set_cell_format ( cell ) header_row , headers = find_header ( ws ) header_labels = [ cell . value for cell in headers ] header_columns = { h . value : h . column for h in headers } next_header_column = max ( list ( header_columns . values ( ) ) + [ 0 ] ) + 1 ref_col , _ = find_header_column ( headers , id_label ) refs = set ( [ ] ) for row in range ( header_row + 1 , ws . max_row + 1 ) : for ref in explode ( ws . cell ( row = row , column = ref_col ) . value ) : refs . add ( ref ) row = ws . max_row + 1 for ref in sorted ( part_fields_dict . keys ( ) ) : if ref not in refs : cell = ws . cell ( row = row , column = ref_col ) cell . value = ref set_cell_format ( cell ) refs . add ( ref ) row += 1 for row in range ( header_row + 1 , ws . max_row + 1 ) : for ref in explode ( ws . cell ( row = row , column = ref_col ) . value ) : try : fields = part_fields_dict [ ref ] for field , value in fields . items ( ) : if value is None : continue try : header = lc_get_close_matches ( field , header_labels , 1 , 0.3 ) [ 0 ] cell = ws . cell ( row = row , column = header_columns [ header ] ) logger . log ( DEBUG_OBSESSIVE , "Updating {} field {} from {} to {}" . format ( ref , field , cell . value , value ) , ) cell . value = value set_cell_format ( cell ) logger . log ( DEBUG_OBSESSIVE , "Type of {} field {} containing {} is {}" . format ( ref , field , cell . value , cell . data_type ) , ) except IndexError : logger . log ( DEBUG_OBSESSIVE , "Adding {} field {} with value {}" . format ( ref , field , value ) , ) cell = ws . cell ( row = row , column = next_header_column ) cell . value = value set_cell_format ( cell ) new_header_cell = ws . cell ( row = header_row , column = next_header_column ) new_header_cell . value = field headers . append ( new_header_cell ) header_labels . append ( field ) header_columns [ field ] = next_header_column next_header_column += 1 except KeyError : pass return wb
Insert the fields in the extracted part dictionary into an XLSX workbook.
Insert the fields in the extracted part dictionary into an XLSX workbook .
"""Insert the fields in the extracted part dictionary into an XLSX workbook.""" # Get all the unique field labels used in the dictionary of part fields. # No workbook given, so create one. # Ungroup any grouped references. # Get the active sheet from the workbook. """Set cell to TEXT format if it contains a string.""" # If the given worksheet is empty, then create one using the part field labels. # Create header row with a column for each part field. # Enter the part references into the part reference column. # Get the header row from the worksheet. # Get column for each header field. # Next open column. Combine with [0] in case there are no headers. # Find the column with the part references. # Add all the missing part references from the field dictionary to the worksheet. # That will ensure a worksheet that only had a subset of the dictionary # part fields will get the missing ones. # Go through each row, see if any reference is in the part dictionary, and # insert/overwrite fields from the dictionary. # Skip None fields. # Match the field name to one of the headers and overwrite the # cell value with the dictionary value. # The dictionary field didn't match any sheet header closely enough, # so add a new column with the field name as the header label. # The part reference doesn't exist in the dictionary.
part_fields_dict
wb
recurse