2017-02-01 2 views
0

별도의 ETL 프로그램에서 사용할 여러 Excel 2007 파일을 포맷하려고합니다. 행 값을 한 레벨 위로 이동하면됩니다. 그래서 행 3의 값을 2 행으로 옮기고 싶습니다.Python openpyxl 행 값을 현재 위치 - 1로 어떻게 이동합니까?

저와 함께하시기 바랍니다. 저는 파이썬과 openpyxl에 멍청한 사람입니다.

이 난에 행을 설정 -1하지만 나는 또한 반복하는 노력이

작동하지 않는 것 (PARAM, PARAM) 워크 시트를 통해 내가 ws.cell을 사용하는 루프 내에서 반복 시도 행 및 루프 내부에서 상위 루프에서 최대 행 1을 시작하고 하위 루프 행의 값을 기본 루프 행에 할당하는 또 다른 반복을 만듭니다. 그러나 이것은 작동하지 않는 것으로 보입니다.

+0

일을 가져옵니다. –

+0

[Python에서 openpyxl을 사용하여 Excel 스프레드 시트에 행 삽입] (http://stackoverflow.com/questions/17299364/insert-row-into-excel-spreadsheet-using-openpyxl-in-python) –

답변

0
from openpyxl import Workbook 
from openpyxl import load_workbook 

wb = load_workbook("sample.xlsx") 

ws1 = wb.active 
ws2 = wb.create_sheet("modifiedSheet") 

start_row = 3 
start_col = 1 

for row in ws1.iter_rows(min_row=start_row): 
    for cell in row: 
     # print(cell.value) 
     ws2.cell(row = start_row-2, column = start_col, value=cell.value) # start_row - 2 will assign the value to the same column up 2 rows 
     start_col += 1 # increment the column, for use of destination sheet 
    start_row += 1 # increment the column, for use of destination sheet 
    start_col = 1 # reset to first column after row processing 

wb.save("modified.xlsx") 

이 동적 아니지만, 당신은 당신의 현재 코드를 포함해야

1

'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'만 사용했습니다. 추가 개발 (및 디버깅)을 맡길 것이지만 문제가 있는지 알려 주시기 바랍니다.

+0

bro, I 이 도움에 감사드립니다. 내 백로 로그가 가라 앉은 후에 시도해 보겠습니다. 고맙습니다. –

+0

특히 위의 스크립트를 사용할 때 ws1.rows [1] 오류가 발생하는 것 같습니다. 내가 이해하는 방식대로 시트는 목록처럼 표현되지 않습니다. 하지만 라인 ws2.append (ws1.rows [i]) 나는 오류가있는 것 같습니다. 그 메시지는 typeError입니다 : 'generator'객체는 subscriptable이 아닙니다 –

+0

저는 파이썬 3.5를 사용하고 있습니다 - 저는 이것이 문제가 될 수 있다고 생각합니다 - 그것이 파이썬 2.x에서 작동하는지 확신 할 수 없습니다. – Amorpheuses

관련 문제