openpyxl을 활용하여 Python에서 엑셀 사용하기

2019. 5. 4. 23:26분석 Python

728x90

일을 할 때 이제 결과물을 정리하기 위해 csv로 저장했다가 이 결과물을 잘 정리하기 위해 다른 엑셀에다가 붙이는 경우가 있었다. 

 

그때는 R을 이용해서 형태를 최대한 유사하게 만든다음 서식복사를 이용해서 했었는데, 

이걸 자동으로 어느정도 맞춰서 하는 방법은 없을까 고민을 하게 되었다.

 

그래서 openxpyxl , xlsxwriter 같은 패키지가 있는 것을 알게 되었다.

나중에 또 보고서를 만들어야 한다면, 저 2개의 패키지 중 괜찮은 것을 써서 최대한 자동화를 해야겠다!

 

import openpyxl 

# import BarChart class from openpyxl.chart sub_module 
from openpyxl.chart import BarChart,Reference 
  
# Call a Workbook() function of openpyxl  
# to create a new blank Workbook object 
wb = openpyxl.Workbook() 
  
# Get workbook active sheet  
# from the active attribute. 
sheet = wb.active 
  
# write o to 9 in 1st column of the active sheet 
for i in range(10): 
    sheet.append([i]) 
## 아하 
values = Reference(sheet, min_col = 1, min_row = 1, 
                         max_col = 1, max_row = 10) 
# Create object of BarChart class 
chart = BarChart() 
  
# adding data to the Bar chart object 
chart.add_data(values) 
# set the title of the chart 
chart.title = " BAR-CHART "
  
# set the title of the x-axis 
chart.x_axis.title = " X_AXIS "
  
# set the title of the y-axis 
chart.y_axis.title = " Y_AXIS "
# add chart to the sheet 
# the top-left corner of a chart 
# is anchored to cell E2 . 
sheet.add_chart(chart, "E2") 
# save the file 
sheet2 = wb.create_sheet("sheet2")
sheet2.title ="change title"
# write o to 9 in 1st column of the active sheet 
for i in range(20): 
    sheet2["B"+ str(i+1) ] = i 


values = Reference(sheet, min_col = 1, min_row = 1, 
                         max_col = 1, max_row = 10) 
  
# Create object of BarChart3D class 
chart = BarChart() 
  
chart.add_data(values) 
  
# set the title of the chart 
chart.title = " BAR-CHART2D "
  
# set the title of the x-axis 
chart.x_axis.title = " X AXIS "
  
# set the title of the y-axis 
chart.y_axis.title = " Y AXIS "
  
# add chart to the sheet 
# the top-left corner of a chart 
# is anchored to cell E2. 
sheet2.add_chart(chart, "E4") 
  
# save the file 
print(wb.sheetnames)
wb.save("barChart.xlsx") 
wb.close()

 

 

728x90