'demo.py'라는 새 파일을 만들고 다음 파일을 에 복사하십시오. 이것은 당신이 원하는 것을 가까이해야합니다. 잘만되면 (사전 요구 사항 검색과 함께) 은 무슨 일이 일어나고 있는지 잘 보여줄 것입니다. 이렇게하면 기존 스프레드 시트와 앞으로 시작해야하는 시작 행이 사용됩니다. 그러면 작업이 수행되고 시작 행 #이 기존 행보다 적 으면 빈 행이 추가되고 나머지 행은 원래 행 번호에 추가됩니다. 안전을 위해 결과를 새로운 통합 문서로 덤프합니다.
import sys
import os
from openpyxl import load_workbook, Workbook
# check that you have 2 command line arguments to use
if len(sys.argv)!=3:
sys.exit("Usage demo.py xls_filename start_line")
# ensure you have an existing file
if not os.path.isfile(sys.argv[1]):
sys.exit("input file does not exist")
excelFile=sys.argv[1]
# make sure the starting row is a number!
if not (sys.argv[2]).isdigit():
sys.exit("2nd argument must be a digit")
num=int(sys.argv[2])
# make sure your extension is okay
root,ext = os.path.splitext(excelFile)
if not ext in ['.xls','.xlsm','.xlsx','.xlsb']:
sys.exit("%s does not have an allowable excel extension"%excelFile)
newExcelFile=root + '_new' + ext
# open the source (1) and destination (2) workbooks & worksheets
wb1 = load_workbook(excelFile)
wb2 = Workbook()
ws1 = wb1.active
ws2 = wb2.active
# move each source row up one in the destination
# starting from row 1 to num
num=min(num,ws1.max_row)
for i in range(1,num):
ws2.append(ws1.rows[i])
if num<ws1.max_row:
# append a blank row
ws2.append(tuple())
# copy the rest of the rows
for i in range(num,ws1.max_row):
ws2.append(ws1.rows[i])
# save the destination workbook
wb2.save(newExcelFile)
소스 워크 시트의 첫 번째 행이 손실되므로주의해야합니다.
여기에 면책 조항을 추가해야합니다. 파이썬이 녹슬었기 때문에 견고성/완성도를 보증 할 수 없으며 비슷한 것을하기 위해 'win32com'만 사용했습니다. 추가 개발 (및 디버깅)을 맡길 것이지만 문제가 있는지 알려 주시기 바랍니다.
일을 가져옵니다. –
[Python에서 openpyxl을 사용하여 Excel 스프레드 시트에 행 삽입] (http://stackoverflow.com/questions/17299364/insert-row-into-excel-spreadsheet-using-openpyxl-in-python) –