programing

파이썬에서 openpyxl을 사용하여 Excel 스프레드시트에 행 삽입

lovejava 2023. 6. 18. 10:01

파이썬에서 openpyxl을 사용하여 Excel 스프레드시트에 행 삽입

저는 openpyxl을 사용하여 스프레드시트에 행을 삽입하는 가장 좋은 방법을 찾고 있습니다.

실제로는 스프레드시트(Excel 2007)에 머리글 행이 있고 그 뒤에 최대 몇 천 행의 데이터가 있습니다.행을 실제 데이터의 첫 번째 행으로 삽입하려고 합니다. 그래서 헤더 뒤에 삽입합니다.추가 기능은 파일 끝에 내용을 추가하는 데 적합한 것으로 알고 있습니다.

openpyxl과 xlrd(및 xlwt)에 대한 설명서를 읽어보면 내용을 수동으로 루프하여 새 시트에 삽입하는 것 외에는 명확한 방법을 찾을 수 없습니다.

Python에 대한 저의 지금까지의 제한된 경험을 고려할 때, 저는 이것이 정말로 선택하기에 가장 좋은 옵션인지 이해하려고 노력하고 있습니다. (가장 피톤적인!) 만약 그렇다면 누군가가 명시적인 예를 제시해 줄 수 있을까요?구체적으로 openpyxl로 행을 읽고 쓸 수 있습니까, 아니면 셀에 액세스해야 합니까?추가로 같은 파일(이름)을 쓸 수 있습니까?

groups.google.com/forum/ #!topic/openpyxl-users/wHGecdQg3Iw 피드백을 기반으로 전체 기능 버전으로 업데이트되었습니다.==

사람들이했듯이, 다른사람지듯이했적이들,이듯▁as지,openpyxl 이기을제않확장습니다했지만는공지하능을 했습니다.Worksheet다음과 같이 클래스를 지정하여 행 삽입을 구현합니다.이것이 다른 사람들에게 유용하다는 것이 증명되기를 바랍니다.

def insert_rows(self, row_idx, cnt, above=False, copy_style=True, fill_formulae=True):
    """Inserts new (empty) rows into worksheet at specified row index.

    :param row_idx: Row index specifying where to insert new rows.
    :param cnt: Number of rows to insert.
    :param above: Set True to insert rows above specified row index.
    :param copy_style: Set True if new rows should copy style of immediately above row.
    :param fill_formulae: Set True if new rows should take on formula from immediately above row, filled with references new to rows.

    Usage:

    * insert_rows(2, 10, above=True, copy_style=False)

    """
    CELL_RE  = re.compile("(?P<col>\$?[A-Z]+)(?P<row>\$?\d+)")

    row_idx = row_idx - 1 if above else row_idx

    def replace(m):
        row = m.group('row')
        prefix = "$" if row.find("$") != -1 else ""
        row = int(row.replace("$",""))
        row += cnt if row > row_idx else 0
        return m.group('col') + prefix + str(row)

    # First, we shift all cells down cnt rows...
    old_cells = set()
    old_fas   = set()
    new_cells = dict()
    new_fas   = dict()
    for c in self._cells.values():

        old_coor = c.coordinate

        # Shift all references to anything below row_idx
        if c.data_type == Cell.TYPE_FORMULA:
            c.value = CELL_RE.sub(
                replace,
                c.value
            )
            # Here, we need to properly update the formula references to reflect new row indices
            if old_coor in self.formula_attributes and 'ref' in self.formula_attributes[old_coor]:
                self.formula_attributes[old_coor]['ref'] = CELL_RE.sub(
                    replace,
                    self.formula_attributes[old_coor]['ref']
                )

        # Do the magic to set up our actual shift    
        if c.row > row_idx:
            old_coor = c.coordinate
            old_cells.add((c.row,c.col_idx))
            c.row += cnt
            new_cells[(c.row,c.col_idx)] = c
            if old_coor in self.formula_attributes:
                old_fas.add(old_coor)
                fa = self.formula_attributes[old_coor].copy()
                new_fas[c.coordinate] = fa

    for coor in old_cells:
        del self._cells[coor]
    self._cells.update(new_cells)

    for fa in old_fas:
        del self.formula_attributes[fa]
    self.formula_attributes.update(new_fas)

    # Next, we need to shift all the Row Dimensions below our new rows down by cnt...
    for row in range(len(self.row_dimensions)-1+cnt,row_idx+cnt,-1):
        new_rd = copy.copy(self.row_dimensions[row-cnt])
        new_rd.index = row
        self.row_dimensions[row] = new_rd
        del self.row_dimensions[row-cnt]

    # Now, create our new rows, with all the pretty cells
    row_idx += 1
    for row in range(row_idx,row_idx+cnt):
        # Create a Row Dimension for our new row
        new_rd = copy.copy(self.row_dimensions[row-1])
        new_rd.index = row
        self.row_dimensions[row] = new_rd
        for col in range(1,self.max_column):
            col = get_column_letter(col)
            cell = self.cell('%s%d'%(col,row))
            cell.value = None
            source = self.cell('%s%d'%(col,row-1))
            if copy_style:
                cell.number_format = source.number_format
                cell.font      = source.font.copy()
                cell.alignment = source.alignment.copy()
                cell.border    = source.border.copy()
                cell.fill      = source.fill.copy()
            if fill_formulae and source.data_type == Cell.TYPE_FORMULA:
                s_coor = source.coordinate
                if s_coor in self.formula_attributes and 'ref' not in self.formula_attributes[s_coor]:
                    fa = self.formula_attributes[s_coor].copy()
                    self.formula_attributes[cell.coordinate] = fa
                # print("Copying formula from cell %s%d to %s%d"%(col,row-1,col,row))
                cell.value = re.sub(
                    "(\$?[A-Z]{1,3}\$?)%d"%(row - 1),
                    lambda m: m.group(1) + str(row),
                    source.value
                )   
                cell.data_type = Cell.TYPE_FORMULA

    # Check for Merged Cell Ranges that need to be expanded to contain new cells
    for cr_idx, cr in enumerate(self.merged_cell_ranges):
        self.merged_cell_ranges[cr_idx] = CELL_RE.sub(
            replace,
            cr
        )

Worksheet.insert_rows = insert_rows

.5+에할 수 있는 v2를 했습니다. v2.5+는 다음과 같습니다.openpyxl:

그리고 또.insert_cols().

insert_rows(idx, amount=1)

row==idx 앞에 행 삽입

원하는 결과를 얻기 위해 지금 사용하고 있는 코드로 이에 답합니다.위치 1에 행을 수동으로 삽입하지만 특정 요구사항에 맞게 조정하기에 충분히 쉬울 것입니다.이 값을 쉽게 조정하여 둘 이상의 행을 삽입하고 관련 위치에서 시작하는 나머지 데이터를 채울 수도 있습니다.

또한 다운스트림 종속성으로 인해 '시트1'의 데이터를 수동으로 지정하고, 원래 워크시트의 이름을 '시트1.5'로 변경하면서 워크시트의 시작 부분에 삽입된 새 시트로 데이터를 복사합니다.

EDIT:서 기본 을 수행하면되는 문제를 사항도 : 편여 : 기집복작기에업이제문형모위거식는해다하제을기해대니결하를한습추변했 format_code 경가사항도든사서본▁edit_code▁i다've▁also▁to에.new_cell.style.number_format.format_code = 'mm/dd/yyyy'저는 이것이 설정 가능하다는 어떤 문서도 찾을 수 없었습니다. 시행착오의 경우에 가까웠습니다!

마지막으로, 이 예는 원본보다 절약하는 것임을 잊지 마십시오.해당되는 경우 저장 경로를 변경하여 이 문제를 방지할 수 있습니다.

    import openpyxl

    wb = openpyxl.load_workbook(file)
    old_sheet = wb.get_sheet_by_name('Sheet1')
    old_sheet.title = 'Sheet1.5'
    max_row = old_sheet.get_highest_row()
    max_col = old_sheet.get_highest_column()
    wb.create_sheet(0, 'Sheet1')

    new_sheet = wb.get_sheet_by_name('Sheet1')

    # Do the header.
    for col_num in range(0, max_col):
        new_sheet.cell(row=0, column=col_num).value = old_sheet.cell(row=0, column=col_num).value

    # The row to be inserted. We're manually populating each cell.
    new_sheet.cell(row=1, column=0).value = 'DUMMY'
    new_sheet.cell(row=1, column=1).value = 'DUMMY'

    # Now do the rest of it. Note the row offset.
    for row_num in range(1, max_row):
        for col_num in range (0, max_col):
            new_sheet.cell(row = (row_num + 1), column = col_num).value = old_sheet.cell(row = row_num, column = col_num).value

    wb.save(file)

Openpyxl 워크시트는 행 또는 열 수준 작업을 수행할 때 기능이 제한됩니다.워크시트에서 행/열과 관련된 유일한 속성은 속성입니다.row_dimensions그리고.column_dimensions각 행과 열에 대해 각각 "행 치수" 및 "열 치수" 개체를 저장합니다.은 이사들또다같음기은사능다용니됩로으과한은전▁like다▁are▁thesearies니사용▁function됩▁also와 같은 기능에도 사용됩니다.get_highest_row()그리고.get_highest_column().

셀됩니다._cells(그리고 사전에서 추적된 그들의 스타일._styles열예: 에서 말한 것과 같습니다.append()).

가장 간단한 방법은 새 시트 작성, 헤더 행 추가, 새 데이터 행 추가, 이전 데이터 행 추가, 이전 데이터 행 삭제, 이전 시트 삭제, 새 시트 이름 변경 등입니다.이 방법에서 발생할 수 있는 문제는 특별히 복사하지 않는 한 행/열 차원 속성 및 셀 스타일의 손실입니다.

또는 행 또는 열을 삽입하는 자체 함수를 만들 수 있습니다.

열을 삭제해야 하는 매우 간단한 워크시트가 많이 있었습니다.명시적인 예를 요청하셨으므로 이를 위해 빠르게 정리한 기능을 제공하겠습니다.

from openpyxl.cell import get_column_letter

def ws_delete_column(sheet, del_column):

    for row_num in range(1, sheet.get_highest_row()+1):
        for col_num in range(del_column, sheet.get_highest_column()+1):

            coordinate = '%s%s' % (get_column_letter(col_num),
                                   row_num)
            adj_coordinate = '%s%s' % (get_column_letter(col_num + 1),
                                       row_num)

            # Handle Styles.
            # This is important to do if you have any differing
            # 'types' of data being stored, as you may otherwise get
            # an output Worksheet that's got improperly formatted cells.
            # Or worse, an error gets thrown because you tried to copy
            # a string value into a cell that's styled as a date.

            if adj_coordinate in sheet._styles:
                sheet._styles[coordinate] = sheet._styles[adj_coordinate]
                sheet._styles.pop(adj_coordinate, None)
            else:
                sheet._styles.pop(coordinate, None)

            if adj_coordinate in sheet._cells:
                sheet._cells[coordinate] = sheet._cells[adj_coordinate]
                sheet._cells[coordinate].column = get_column_letter(col_num)
                sheet._cells[coordinate].row = row_num
                sheet._cells[coordinate].coordinate = coordinate

                sheet._cells.pop(adj_coordinate, None)
            else:
                sheet._cells.pop(coordinate, None)

        # sheet.garbage_collect()

작업 중인 워크시트와 삭제할 열 번호를 전달하고 제거합니다.그것이 정확히 당신이 원했던 것이 아니라는 것을 알지만, 이 정보가 도움이 되었기를 바랍니다!

편집: 누군가가 이것을 또 한 번 투표한 것을 보고 업데이트해야겠다고 생각했습니다.Openpyxl의 좌표계는 지난 몇 년 동안 어느 정도 변화를 경험했고, 도입되었습니다.coordinate항목의 속성_cell이것도 편집해야 합니다. 그렇지 않으면 행이 삭제되지 않고 공백으로 남아 Excel이 파일 문제에 대한 오류를 발생시킵니다.이것은 Openpyxl 2.2.3(이후 버전에서는 테스트되지 않음)에서 작동합니다.

openpyxl 1.5부터는 이제 .insert_rows(idx, row_qty)를 사용할 수 있습니다.

from openpyxl import load_workbook
wb = load_workbook('excel_template.xlsx')
ws = wb.active
ws.insert_rows(14, 10)

엑셀에서 수동으로 했을 때처럼 idx 행의 형식을 선택하지 않습니다.나중에 올바른 포맷, 즉 셀 색상을 적용해야 합니다.

Python에서 openpyxl을 사용하여 Excel 스프레드시트에 행을 삽입하려면 다음과 같이 하십시오.

아래 코드가 도움이 될 수 있습니다:

import openpyxl

file = "xyz.xlsx"
#loading XL sheet bassed on file name provided by user
book = openpyxl.load_workbook(file)
#opening sheet whose index no is 0
sheet = book.worksheets[0]

#insert_rows(idx, amount=1) Insert row or rows before row==idx, amount will be no of 
#rows you want to add and it's optional
sheet.insert_rows(13)

열을 삽입할 때도 openpyxl은 insert_cols(idx, 양=1)와 같은 유사한 함수를 갖습니다.

저는 스프레드시트의 원하는 위치에 행 전체를 삽입하거나 2D 테이블 전체를 openpyxl로 삽입하는 기능을 작성했습니다.

함수의 모든 행은 설명과 함께 설명되지만, 하나의 행만 삽입하려면 행을 [행]과 동일하게 만들기만 하면 됩니다.즉, 행 = [1,2,3,4,5]인 경우 입력을 [1,2,3,4,5]로 설정합니다.이 행을 스프레드시트의 맨 위 행(A1)에 삽입하려면 시작 = [1,1]입니다.

파일 이름을 덮어쓸 수 있습니다. 맨 아래에 있는 예를 참조하십시오.

def InputList(Start, List): #This function is to input an array/list from a input start point; len(Start) must equal 2, where Start = [1,1] is cell 1A. List must be a two dimensional array; if you wish to input a single row then this can be done where len(List) == 1, e.g. List = [[1,2,3,4]]
    x = 0 #Sets up a veriable to go through List columns
    y = 0 #Sets up a veriable to go through List rows
    l = 0 #Sets up a veriable to count addional columns against Start[1] to allow for column reset on each new row
    for row in List: #For every row in List
        l = 0 #Set additonal columns to zero
        for cell in row: #For every cell in row
            ws.cell(row=Start[0], column=Start[1]).value = List[y][x] #Set value for current cell
            x = x + 1 #Move to next data input (List) column
            Start[1] = Start[1] + 1 #Move to next Excel column
            l = l + 1 #Count addional row length
        y = y + 1 #Move to next Excel row
        Start[0] = Start[0] + 1 #Move to next Excel row
        x = 0 #Move back to first column of input data (ready for next row)
        Start[1] = Start[1] - l #Reset Excel column back to orignal start column, ready to write next row

7행의 시작 부분에 단일 행이 삽입되는 예:

from openpyxl import load_workbook
wb = load_workbook('New3.xlsx')
ws = wb.active

def InputList(Start, List): #This function is to input an array/list from a input start point; len(Start) must equal 2, where Start = [1,1] is cell 1A. List must be a two dimensional array; if you wish to input a single row then this can be done where len(List) == 1, e.g. List = [[1,2,3,4]]
    x = 0 #Sets up a veriable to go through List columns
    y = 0 #Sets up a veriable to go through List rows
    l = 0 #Sets up a veriable to count addional columns against Start[1] to allow for column reset on each new row
    for row in List: #For every row in List
        l = 0 #Set additonal columns to zero
        for cell in row: #For every cell in row
            ws.cell(row=Start[0], column=Start[1]).value = List[y][x] #Set value for current cell
            x = x + 1 #Move to next data input (List) column
            Start[1] = Start[1] + 1 #Move to next Excel column
            l = l + 1 #Count addional row length
        y = y + 1 #Move to next Excel row
        Start[0] = Start[0] + 1 #Move to next Excel row
        x = 0 #Move back to first column of input data (ready for next row)
        Start[1] = Start[1] - l #Reset Excel column back to orignal start column, ready to write next row

test = [[1,2,3,4]]
InputList([7,1], test)

wb.save('New3.xlsx')

Dallas 솔루션을 도입하여 병합된 셀에 대한 지원을 추가했습니다.

    def insert_rows(self, row_idx, cnt, above=False, copy_style=True, fill_formulae=True):
        skip_list = []
        try:
            idx = row_idx - 1 if above else row_idx
            for (new, old) in zip(range(self.max_row+cnt,idx+cnt,-1),range(self.max_row,idx,-1)):
                for c_idx in range(1,self.max_column):
                  col = self.cell(row=1, column=c_idx).column #get_column_letter(c_idx)
                  print("Copying %s%d to %s%d."%(col,old,col,new))
                  source = self["%s%d"%(col,old)]
                  target = self["%s%d"%(col,new)]
                  if source.coordinate in skip_list:
                      continue

                  if source.coordinate in self.merged_cells:
                      # This is a merged cell
                      for _range in self.merged_cell_ranges:
                          merged_cells_list = [x for x in cells_from_range(_range)][0]
                          if source.coordinate in merged_cells_list:
                              skip_list = merged_cells_list
                              self.unmerge_cells(_range)
                              new_range = re.sub(str(old),str(new),_range)
                              self.merge_cells(new_range)
                              break

                  if source.data_type == Cell.TYPE_FORMULA:
                    target.value = re.sub(
                      "(\$?[A-Z]{1,3})%d"%(old),
                      lambda m: m.group(1) + str(new),
                      source.value
                    )
                  else:
                    target.value = source.value
                  target.number_format = source.number_format
                  target.font   = source.font.copy()
                  target.alignment = source.alignment.copy()
                  target.border = source.border.copy()
                  target.fill   = source.fill.copy()
            idx = idx + 1
            for row in range(idx,idx+cnt):
                for c_idx in range(1,self.max_column):
                  col = self.cell(row=1, column=c_idx).column #get_column_letter(c_idx)
                  #print("Clearing value in cell %s%d"%(col,row))
                  cell = self["%s%d"%(col,row)]
                  cell.value = None
                  source = self["%s%d"%(col,row-1)]
                  if copy_style:
                    cell.number_format = source.number_format
                    cell.font      = source.font.copy()
                    cell.alignment = source.alignment.copy()
                    cell.border    = source.border.copy()
                    cell.fill      = source.fill.copy()
                  if fill_formulae and source.data_type == Cell.TYPE_FORMULA:
                    #print("Copying formula from cell %s%d to %s%d"%(col,row-1,col,row))
                    cell.value = re.sub(
                      "(\$?[A-Z]{1,3})%d"%(row - 1),
                      lambda m: m.group(1) + str(row),
                      source.value
                    )

Nick의 솔루션을 편집한 이 버전에서는 시작 행, 삽입할 행 수 및 파일 이름을 사용하고 필요한 수의 빈 행을 삽입합니다.

#! python 3

import openpyxl, sys

my_start = int(sys.argv[1])
my_rows = int(sys.argv[2])
str_wb = str(sys.argv[3])

wb = openpyxl.load_workbook(str_wb)
old_sheet = wb.get_sheet_by_name('Sheet')
mcol = old_sheet.max_column
mrow = old_sheet.max_row
old_sheet.title = 'Sheet1.5'
wb.create_sheet(index=0, title='Sheet')

new_sheet = wb.get_sheet_by_name('Sheet')

for row_num in range(1, my_start):
    for col_num in range(1, mcol + 1):
        new_sheet.cell(row = row_num, column = col_num).value = old_sheet.cell(row = row_num, column = col_num).value

for row_num in range(my_start + my_rows, mrow + my_rows):
    for col_num in range(1, mcol + 1):
        new_sheet.cell(row = (row_num + my_rows), column = col_num).value = old_sheet.cell(row = row_num, column = col_num).value

wb.save(str_wb)

이것은 저에게 효과가 있었습니다.

    openpyxl.worksheet.worksheet.Worksheet.insert_rows(wbs,idx=row,amount=2)

row==idx 앞에 두 행 삽입

참조: http://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html

저는 openpyxl 3.0.9에 대한 몇 가지 수정 사항이 있음에도 불구하고 Dallas의 답변을 성공적으로 사용할 수 있었습니다.2022년에 어떻게 해야 할지 궁금해하는 다른 사람들을 위해 코드를 여기에 올립니다.

차이점은 다음과 같습니다.

  • 가져오기 추가
  • 변화하는Cell.TYPE_FORMULA로.TYPE_FORMULA
  • 다음을 사용하여 유형 변환 추가str()또는int()필요한 곳에
  • 정의된 이름 업데이트 중

저는 파이썬이 처음이라 이것에 대한 변경 사항을 자유롭게 제안할 수 있지만, 이것이 제가 작동하게 만든 방법입니다.

import copy
import re
from openpyxl.utils import get_column_letter
from openpyxl.cell.cell import TYPE_FORMULA

#https://stackoverflow.com/questions/17299364/insert-row-into-excel-spreadsheet-using-openpyxl-in-python#71195832
def insert_rows(self, row_idx, cnt, above=True, copy_style=True, fill_formulae=True):
    """Inserts new (empty) rows into worksheet at specified row index.

    :param self: Worksheet
    :param row_idx: Row index specifying where to insert new rows.
    :param cnt: Number of rows to insert.
    :param above: Set True to insert rows above specified row index.
    :param copy_style: Set True if new rows should copy style of immediately above row.
    :param fill_formulae: Set True if new rows should take on formula from immediately above row, filled with references new to rows.

    Usage:

    * insert_rows(2, 10, above=True, copy_style=False)

    """
    CELL_RE  = re.compile("(?P<col>\$?[A-Z]+)(?P<row>\$?\d+)")

    row_idx = row_idx - 1 if above else row_idx

    def replace(m):
        row = m.group('row')
        prefix = "$" if row.find("$") != -1 else ""
        row = int(row.replace("$",""))
        row += cnt if row > row_idx else 0
        return m.group('col') + prefix + str(row)

    # First, we shift all cells down cnt rows...
    old_cells = set()
    old_fas   = set()
    new_cells = dict()
    new_fas   = dict()
    for c in self._cells.values():

        old_coor = c.coordinate

        # Shift all references to anything below row_idx
        if c.data_type == TYPE_FORMULA:
            c.value = CELL_RE.sub(
                replace,
                c.value
            )
            # Here, we need to properly update the formula references to reflect new row indices
            if old_coor in self.formula_attributes and 'ref' in self.formula_attributes[old_coor]:
                self.formula_attributes[old_coor]['ref'] = CELL_RE.sub(
                    replace,
                    self.formula_attributes[old_coor]['ref']
                )

        # Do the magic to set up our actual shift    
        if c.row > row_idx:
            old_coor = c.coordinate
            old_cells.add((c.row,c.column))
            c.row += cnt
            new_cells[(c.row,c.column)] = c
            if old_coor in self.formula_attributes:
                old_fas.add(old_coor)
                fa = self.formula_attributes[old_coor].copy()
                new_fas[c.coordinate] = fa

    for coor in old_cells:
        del self._cells[coor]
    self._cells.update(new_cells)

    for fa in old_fas:
        del self.formula_attributes[fa]
    self.formula_attributes.update(new_fas)

    # Next, we need to shift all the Row Dimensions below our new rows down by cnt...
    for row in range(len(self.row_dimensions)-1+cnt,row_idx+cnt,-1):
        new_rd = copy.copy(self.row_dimensions[row-cnt])
        new_rd.index = row
        self.row_dimensions[row] = new_rd
        del self.row_dimensions[row-cnt]

    # Now, create our new rows, with all the pretty cells
    row_idx += 1
    for row in range(row_idx,row_idx+cnt):
        # Create a Row Dimension for our new row
        new_rd = copy.copy(self.row_dimensions[row-1])
        new_rd.index = row
        self.row_dimensions[row] = new_rd
        for col in range(1,self.max_column):
            col = get_column_letter(col)
            cell = self[str(col)+str(row)]
            cell.value = None
            source = self[str(col)+str(row-1)]
            if copy_style:
                cell.number_format = source.number_format
                cell.font      = copy.copy(source.font)
                cell.alignment = copy.copy(source.alignment)
                cell.border    = copy.copy(source.border)
                cell.fill      = copy.copy(source.fill)
            if fill_formulae and source.data_type == TYPE_FORMULA:
                s_coor = source.coordinate
                if s_coor in self.formula_attributes and 'ref' not in self.formula_attributes[s_coor]:
                    fa = self.formula_attributes[s_coor].copy()
                    self.formula_attributes[cell.coordinate] = fa
                # print("Copying formula from cell %s%d to %s%d"%(col,row-1,col,row))
                cell.value = re.sub(
                    "(\$?[A-Z]{1,3}\$?)%d"%(row - 1),
                    lambda m: m.group(1) + str(row),
                    source.value
                )   
                cell.data_type = TYPE_FORMULA

    # Check for Merged Cell Ranges that need to be expanded to contain new cells
    for cr_idx, cr in enumerate(self.merged_cells.ranges):
        self.merged_cells.ranges[cr_idx] = CELL_RE.sub(
            replace,
            str(cr)
        )

    # Update all defined names
    wb :Workbook = self.parent
    for definedName in wb.defined_names.definedName:
        ref :str = definedName.attr_text
        parts = ref.split("!")
        if parts[0].strip("'") == self.title:
            definedName.attr_text = CELL_RE.sub(replace, ref)

불행하게도 파일에서 읽는 것보다 더 좋은 방법은 없습니다. xlwt와 같은 라이브러리를 사용하여 새 엑셀 파일을 작성합니다(새 행이 맨 위에 삽입됨).Excel은 읽고 추가할 수 있는 데이터베이스처럼 작동하지 않습니다.불행하게도 당신은 정보를 읽고 메모리를 조작하고 본질적으로 새로운 파일을 쓰기만 하면 됩니다.

언급URL : https://stackoverflow.com/questions/17299364/insert-row-into-excel-spreadsheet-using-openpyxl-in-python