언어/Python

python openpyxl write list to cell

darkdevilness 2017. 9. 7. 00:57
728x90

save_openpyxl.py


code---------

코드에 대한  자세한 설명은 다른 블러그를 참조하세요  

openpyxl에서  리스트 를  cell에  쓰는 것 입니다.    1차 리스트 , 2차 리스트 모두 사용하는 예제입니다.

가로로 또는 세로로 쓰고 싶다면   row / column 값을  교환 (swap ) 하면됩니다. 

openplxl 모듈을 사용하실 때   test 파일 이름을  openpyxl.py 로 하시면 안됩니다.   impport openpyxl 에서 함수 를 찾을 수 없다고 나옵니다 그래서 python에서는 파일명을 모듈명과 동일하게 사용하지 않아야 합니다. ( 이유는  찾아 보세요 )

'''

Created on 2017. 9. 6.


@author: HOME

'''


import os,glob

import openpyxl

from openpyxl import Workbook 

from openpyxl import load_workbook 


if __name__ == '__main__':

    pass


excel_file='data1.xlsx'


if not (os.path.isfile(excel_file)):

#if not glob.glob(excel_file) :

    wb = openpyxl.Workbook()

else:

    wb = openpyxl.load_workbook(excel_file)

ws = wb.active

#ws=wb.get_sheet_by_name(ws_activename)

print(ws.title)

work_list=wb.get_sheet_names()

print(work_list)

ws_activename='tx'

if not ws_activename in work_list :

    ws = wb.create_sheet(index=2,title=ws_activename)

ws_activename='rx'

if not ws_activename in work_list :

    ws = wb.create_sheet(index=1,title=ws_activename)  

print(wb.get_sheet_names())


ws=wb[ws_activename]

ws=wb.get_sheet_by_name(ws_activename)

print(ws.title)

#wb.remove_sheet(ws) # remove worksheet

#ws.title='txtx' # changel worksheet name


datalist=[['title'],['a','b','c','d','e'],[1,2,3,4,5],[6,7,8,9,0],['']]


work_list=wb.get_sheet_names()

ws=wb[work_list[0]] 

for c in range(0,len(work_list)):

    ws.cell(row=1,column=c+1).value=work_list[c]


ws=wb[work_list[2]] 

ws['A1']='TITLE: HI~~~ '

max_row=ws.max_row;max_column=ws.max_column

for r in range(0,len(datalist)):

    row=r+max_row+1;

    for c in range(0,len(datalist[r])):

        column=c+1;

        ws.cell(row=row,column=column).value=datalist[r][c]

        print('(',row,column,")=",datalist[r][c])

    

for ws_activename in wb.get_sheet_names():

    ws=wb.get_sheet_by_name(ws_activename)


    print(ws.max_row," ",ws.max_column)

    #for r in ws.rows:

    #    print( r[0].value)

    #for c in ws.columns:

    #    print(  c[0].value,end=' ')


wb.save(excel_file)

wb.close()

728x90