Inย [3]:
from openpyxl import Workbook
import random
wb = Workbook()
ws = wb.active
ws.title = 'data'
ws.append(['์๋ฒ','์ ํ๋ช
','๊ฐ๊ฒฉ','์๋','ํฉ๊ณ'])
name_list = ['๊ธฐ๊ณ์ ํค๋ณด๋','๊ฒ์ด๋ฐ ๋ง์ฐ์ค','32์ธ์น ๋ชจ๋ํฐ','๋ง์ฐ์ค ํจ๋','ํค๋ํฐ','๊ฒ์ด๋ฐ ์์']
for i in range(random.randint(5,10)):
name = random.choice(name_list)
if name == '๊ธฐ๊ณ์ ํค๋ณด๋':
price = 120000
elif name == '๊ฒ์ด๋ฐ ๋ง์ฐ์ค':
price = 40000
elif name == '32์ธ์น ๋ชจ๋ํฐ':
price = 350000
elif name == '๋ง์ฐ์ค ํจ๋':
price = 20000
elif name == 'ํค๋ํฐ':
price = 80000
elif name == '๊ฒ์ด๋ฐ ์์':
price = 200000
quantity = random.randint(1,5)
ws.append([i+1,name,price,quantity,f'=C{i+2}*D{i+2}'])
#wb.save('์์
์๋ํ/์ค๋งํธ์คํ ์ด.xlsx')
#wb.save('์์
์๋ํ/11๋ฒ๊ฐ.xlsx')
wb.save('์์
์๋ํ/์ฟ ํก.xlsx')
wb.close()
Inย [38]:
import win32com.client
import os
from openpyxl import Workbook, load_workbook
# file_path = "์์
์๋ํ/์ค๋งํธ์คํ ์ด.xlsx"
# file_path = "์์
์๋ํ/11๋ฒ๊ฐ.xlsx"
file_path = "์์
์๋ํ/์ฟ ํก.xlsx"
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
ewb = excel.Workbooks.Open(os.path.abspath(file_path))
ewb.Application.Calculate()
ewb.Save()
ewb.Close()
excel.Quit()
wb = load_workbook(file_path, data_only=True) # ์์์ ๊ณ์ฐ ๊ฒฐ๊ณผ๋ง ์ฝ์
ws = wb['data']
# # ํ๊ณผ ์ด ๊ฐ์๋ฅผ ๋ชจ๋ ์๋ ๊ฒฝ์ฐ
# for x in range(1, 6+1):
# for y in (range(1, 5 +1)):
# print(ws.cell(row=x,column=y).value,end=' ')
# print()
#ํ๊ณผ ์ด ๊ฐ์๋ฅผ ๋ชจ๋ฅผ ๊ฒฝ์ฐ
for x in range(1, ws.max_row+1):
for y in (range(1, ws.max_column +1)):
print(ws.cell(row=x,column=y).value,end=' ')
print()
์๋ฒ ์ ํ๋ช ๊ฐ๊ฒฉ ์๋ ํฉ๊ณ 1 32์ธ์น ๋ชจ๋ํฐ 350000 3 1050000 2 32์ธ์น ๋ชจ๋ํฐ 350000 1 350000 3 ๊ธฐ๊ณ์ ํค๋ณด๋ 120000 3 360000 4 ๊ธฐ๊ณ์ ํค๋ณด๋ 120000 1 120000 5 ๊ฒ์ด๋ฐ ์์ 200000 2 400000 6 ๊ธฐ๊ณ์ ํค๋ณด๋ 120000 1 120000 7 32์ธ์น ๋ชจ๋ํฐ 350000 4 1400000
Inย [39]:
# for row in ws.rows:
# print(row)
# print("="*100)
# iter_rows()๊ฐ ๋ฉ๋ชจ๋ฆฌ ํจ์จ์ด ๋ ์ข์
for row in ws.iter_rows():
# for cell in row:
# print(cell.value)
print([cell.value for cell in row])
['์๋ฒ', '์ ํ๋ช ', '๊ฐ๊ฒฉ', '์๋', 'ํฉ๊ณ'] [1, '32์ธ์น ๋ชจ๋ํฐ', 350000, 3, 1050000] [2, '32์ธ์น ๋ชจ๋ํฐ', 350000, 1, 350000] [3, '๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 3, 360000] [4, '๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 1, 120000] [5, '๊ฒ์ด๋ฐ ์์', 200000, 2, 400000] [6, '๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 1, 120000] [7, '32์ธ์น ๋ชจ๋ํฐ', 350000, 4, 1400000]
Inย [40]:
for row in ws.iter_rows(min_row=2, max_row=6):
print([cell.value for cell in row])
[1, '32์ธ์น ๋ชจ๋ํฐ', 350000, 3, 1050000] [2, '32์ธ์น ๋ชจ๋ํฐ', 350000, 1, 350000] [3, '๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 3, 360000] [4, '๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 1, 120000] [5, '๊ฒ์ด๋ฐ ์์', 200000, 2, 400000]
Inย [41]:
# ์กฐ๊ฑด์ด ํ์ํ ๋ ์ฌ์ฉํ๋ฉด ์ข์
for row in ws.iter_rows(min_row=2, max_row=6, min_col=2, max_col=4):
print([cell.value for cell in row])
['32์ธ์น ๋ชจ๋ํฐ', 350000, 3] ['32์ธ์น ๋ชจ๋ํฐ', 350000, 1] ['๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 3] ['๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 1] ['๊ฒ์ด๋ฐ ์์', 200000, 2]
Inย [42]:
for row in ws.iter_rows():
print(row)
(<Cell 'data'.A1>, <Cell 'data'.B1>, <Cell 'data'.C1>, <Cell 'data'.D1>, <Cell 'data'.E1>) (<Cell 'data'.A2>, <Cell 'data'.B2>, <Cell 'data'.C2>, <Cell 'data'.D2>, <Cell 'data'.E2>) (<Cell 'data'.A3>, <Cell 'data'.B3>, <Cell 'data'.C3>, <Cell 'data'.D3>, <Cell 'data'.E3>) (<Cell 'data'.A4>, <Cell 'data'.B4>, <Cell 'data'.C4>, <Cell 'data'.D4>, <Cell 'data'.E4>) (<Cell 'data'.A5>, <Cell 'data'.B5>, <Cell 'data'.C5>, <Cell 'data'.D5>, <Cell 'data'.E5>) (<Cell 'data'.A6>, <Cell 'data'.B6>, <Cell 'data'.C6>, <Cell 'data'.D6>, <Cell 'data'.E6>) (<Cell 'data'.A7>, <Cell 'data'.B7>, <Cell 'data'.C7>, <Cell 'data'.D7>, <Cell 'data'.E7>) (<Cell 'data'.A8>, <Cell 'data'.B8>, <Cell 'data'.C8>, <Cell 'data'.D8>, <Cell 'data'.E8>)
Inย [43]:
for row in ws.iter_rows(min_row=2, values_only=True):
# print(list(row))
print(row)
(1, '32์ธ์น ๋ชจ๋ํฐ', 350000, 3, 1050000) (2, '32์ธ์น ๋ชจ๋ํฐ', 350000, 1, 350000) (3, '๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 3, 360000) (4, '๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 1, 120000) (5, '๊ฒ์ด๋ฐ ์์', 200000, 2, 400000) (6, '๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 1, 120000) (7, '32์ธ์น ๋ชจ๋ํฐ', 350000, 4, 1400000)
Inย [44]:
for row in ws.iter_rows(min_row=2, max_row=ws.max_row, min_col=2, max_col=ws.max_column):
# print(tuple([cell.value for cell in row]))
print([cell.value for cell in row])
['32์ธ์น ๋ชจ๋ํฐ', 350000, 3, 1050000] ['32์ธ์น ๋ชจ๋ํฐ', 350000, 1, 350000] ['๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 3, 360000] ['๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 1, 120000] ['๊ฒ์ด๋ฐ ์์', 200000, 2, 400000] ['๊ธฐ๊ณ์ ํค๋ณด๋', 120000, 1, 120000] ['32์ธ์น ๋ชจ๋ํฐ', 350000, 4, 1400000]
Inย [55]:
## ๋ฌธ์ ์ทจํฉ
from openpyxl import Workbook, load_workbook
import win32com.client
import os
total_wb = Workbook()
total_ws = total_wb.active
total_ws.title = 'data'
total_ws.append(['์๋ฒ','์ ํ๋ช
','๊ฐ๊ฒฉ','์๋','ํฉ๊ณ'])
file_list = ['์ค๋งํธ์คํ ์ด','11๋ฒ๊ฐ','์ฟ ํก']
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
for file in file_list:
file_path = f'์์
์๋ํ/{file}.xlsx'
ewb = excel.Workbooks.Open(os.path.abspath(file_path))
ewb.Application.Calculate()
ewb.Save()
ewb.Close()
wb = load_workbook(file_path, data_only=True)
ws = wb.active
for row in ws.iter_rows(min_row=2):
# data = []
# for cell in row:
# data.append(cell.value)
# total_ws.append(data)
total_ws.append([cell.value for cell in row])
excel.Quit()
for i, cell in enumerate(total_ws['A'][1:], start = 1):
cell.value = i
total_wb.save('์์
์๋ํ/total.xlsx')
total_wb.close()
Inย [88]:
## ์ ํ ๋ถ๋ฆฌ (ํญ๋ณ๋ก)
from openpyxl import Workbook, load_workbook
wb = load_workbook('์์
์๋ํ/total.xlsx')
ws = wb.active
tab = []
# ์ ํ์ด๋ฆ ๋ฆฌ์คํธ ๊ฐ์ ธ์ค๊ธฐ
for i, cell in enumerate(ws['B'][1:], start = 1):
tab.append(cell.value)
sheet = list(set(tab))
for i in range(len(sheet)):
wb.create_sheet(sheet[i]) # ์ ํ๋ช
์ ๋ฐ๋ฅธ ์ํธ ์ถ๊ฐ
for row in ws.iter_rows(min_row=2,min_col=2):
data = []
if row[0].value == sheet[i]: # ์ํธ์ ๊ฐ์ ์ ํ๋ช
์ ๊ฐ์ง ํ๋ง ๋ฝ๊ณ , ๊ทธ ํ๋ค์ ์ํธ์ ์ถ๊ฐ
for cell in row:
data.append(cell.value)
wb[sheet[i]].append(data)
wb.save('์์
์๋ํ/total_1.xlsx')
wb.close()
'''## ๊ฐ์ฌ๋ ์ฝ๋ฉ 1
name_list = []
# ์ ํ์ด๋ฆ ๋ฆฌ์คํธ(์ํธํญ ์์ฑ)
for row in ws.iter_rows(min_row=2,min_col=2):
name = row[0].value
if name not in name_list:
name_list.append(name)
wb.create_sheet(name)
wb[name].append([cell.value for cell in row])
wb.save('์์
์๋ํ/total_2.xlsx')
wb.close()'''
'''## ๊ฐ์ฌ๋ ์ฝ๋ฉ 2
name_list = list(set([cell.value for cell in ws['B'][1:]]))
for name in name_list:
wb.create_sheet(name)
for row in ws.iter_rows(min_row=2,min_col=2):
wb[row[0].value].append([cell.value for cell in row])
wb.save('์์
์๋ํ/total_3.xlsx')
wb.close()'''
Out[88]:
"## ๊ฐ์ฌ๋ ์ฝ๋ฉ 2\nname_list = list(set([cell.value for cell in ws['B'][1:]]))\nfor name in name_list:\n wb.create_sheet(name)\n\nfor row in ws.iter_rows(min_row=2,min_col=2):\n wb[row[0].value].append([cell.value for cell in row])\n\nwb.save('์์ ์๋ํ/total_3.xlsx')\nwb.close()"
Inย [92]:
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font, Side, Border, Alignment
file_path = '์์
์๋ํ/total_1.xlsx'
save_path = '์์
์๋ํ/total_last.xlsx'
wb = load_workbook(file_path)
#ws = wb.active
ws = wb['data']
## ์ด ๋๋น ๋ณ๊ฒฝ
ws.column_dimensions['B'].width = 20 # ๋ฌธ์์ ๊ธฐ์ค
# ws.column_dimensions['B'].hidden = True # ์ด ์จ๊ธฐ๊ธฐ
# ws.column_dimensions['B'].bestfit = True # ์ด ๋๋น ์๋ ์กฐ์
## ํ ๋์ด ๋ณ๊ฒฝ
ws.row_dimensions[1].height = 30 # ํฌ์ธํธ ๊ธฐ์ค (๊ธ์ํฌ๊ธฐ)
## ํฐํธ ๋ณ๊ฒฝ
ft = Font(size=12, color='0077ff', bold=True, name='๋์')
ws['A1'].font = ft
## ์ ์์ฑ
border_type1 = Side(color='000000', border_style='thin')
border_type2 = Side(color='000000', border_style='thick')
## ์ ์ง์
border_bottom = Border(bottom = border_type1) # left, right, top, bottom
ws['A4'].border = border_bottom
border_all = Border(left = border_type2, right = border_type2, top = border_type2, bottom = border_type2)
ws['B4'].border = border_all
## ์ ๋ ฌ ์ง์
alignment_type = Alignment(horizontal='center',vertical='center')
## horizontal(์ํ์ ๋ ฌ) : left, center, right, justify
## vertical(์์ง์ ๋ ฌ) : top, center, bottom
ws['B5'].alignment = alignment_type
for row in ws.iter_rows(max_row=1):
for cell in row:
cell.alignment = alignment_type
cell.border = border_bottom
cell.font = ft
wb.save(save_path)
wb.close
Out[92]:
<bound method Workbook.close of <openpyxl.workbook.workbook.Workbook object at 0x0000020709833DD0>>
Inย [110]:
from openpyxl import Workbook
import random
from datetime import datetime, timedelta
wb = Workbook()
ws = wb.active
ws.title = 'data'
ws.append(['๋ ์ง','์ํ๋ช
','์๋','๊ธ์ก'])
name_list = ['๋ง์ฐ์ค','๋ชจ๋ํฐ','๋
ธํธ๋ถ','ํค๋ํฐ']
k=0
for i in range(random.randint(5,10)):
name = random.choice(name_list)
day = datetime(2024,1,1)+timedelta(days=i)
date = day.strftime('%Y-%m-%d')
if name == '๋ง์ฐ์ค':
price = random.randint(10000,100000)
elif name == '๋ชจ๋ํฐ':
price = random.randint(10000,100000)
elif name == '๋
ธํธ๋ถ':
price = random.randint(10000,100000)
elif name == 'ํค๋ํฐ':
price = (random.randint(10000,10000000) // 10) * 10
k+=1
quantity = random.randint(1,5)
ws.append([date,name,quantity,price])
# wb.save('์์
์๋ํ/sample_file_1.xlsx')
#wb.save('์์
์๋ํ/sample_file_2.xlsx')
# wb.save('์์
์๋ํ/sample_file_3.xlsx')
wb.close()
Inย [113]:
## ๋ฌธ์ ์ทจํฉ ํ ์ ๋ ฌ
from openpyxl import Workbook, load_workbook
import win32com.client
import os
total_wb = Workbook()
total_ws = total_wb.active
total_ws.title = 'data'
file_list = ['sample_file_1','sample_file_2','sample_file_3']
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
total_ws.append(['๋ ์ง','์ํ๋ช
','์๋','๊ธ์ก'])
for file in file_list:
file_path = f'์์
์๋ํ/{file}.xlsx'
ewb = excel.Workbooks.Open(os.path.abspath(file_path))
ewb.Application.Calculate()
ewb.Save()
ewb.Close()
wb = load_workbook(file_path, data_only=True)
ws = wb.active
for row in ws.iter_rows(min_row=2):
# data = []
# for cell in row:
# data.append(cell.value)
# total_ws.append(data)
total_ws.append([cell.value for cell in row])
data.sort(key=lambda row:row[0])
excel.Quit()
#total_wb.save('์์
์๋ํ/merged_files.xlsx')
total_wb.save('์์
์๋ํ/merged_files1.xlsx')
total_wb.close()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[113], line 14 11 file_list = ['sample_file_1','sample_file_2','sample_file_3'] 13 excel = win32com.client.Dispatch("Excel.Application") ---> 14 excel.Visible = False 15 total_ws.append(['๋ ์ง','์ํ๋ช ','์๋','๊ธ์ก']) 16 for file in file_list: File ~\anaconda\Lib\site-packages\win32com\client\dynamic.py:707, in CDispatch.__setattr__(self, attr, value) 705 except pythoncom.com_error: 706 pass --> 707 raise AttributeError( 708 "Property '%s.%s' can not be set." % (self._username_, attr) 709 ) AttributeError: Property 'Excel.Application.Visible' can not be set.
Inย [130]:
from openpyxl import Workbook
import random
from datetime import datetime, timedelta
wb = Workbook()
ws = wb.active
ws.title = 'data'
ws.append(['๋ ์ง','๋งค์ถ์ก','๋น์ฉ','์ด์ต'])
for i in range(365+1):
day = datetime(2024,1,1)+timedelta(days=i)
date = day.strftime('%Y-%m-%d')
money1 = (random.randint(10000,500000)//10)*10
money2 = (random.randint(10000,100000)//10)*10
money3 = money1-money2
ws.append([date,money1,money2,money3])
wb.save('์์
์๋ํ/sales_data_sample.xlsx')
wb.close()
Inย [132]:
## ์๋ณ ๊ณ์ฐ
from openpyxl import Workbook, load_workbook
import win32com.client
import os
total_wb = Workbook()
total_ws = total_wb.active
total_ws.title = 'data'
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
total_ws.append(['์','๋งค์ถ์ก','๋น์ฉ','์ด์ต'])
file_path = f'์์
์๋ํ/sales_data_sample.xlsx'
ewb = excel.Workbooks.Open(os.path.abspath(file_path))
ewb.Application.Calculate()
ewb.Save()
ewb.Close()
wb = load_workbook(file_path, data_only=True)
ws = wb.active
total1 = 0
total2 = 0
total3 = 0
for j in range(1,13):
for row in ws.iter_rows():
if f'2024-{j:02d}' in row[0].value:
total1 += row[1].value
total2 += row[2].value
total3 += row[3].value
total_ws.append([f'2024-{j:02d}',total1,total2,total3])
excel.Quit()
total_wb.save('์์
์๋ํ/sales_report.xlsx')
total_wb.close()
Inย [142]:
## ๋ฌธ์ ์คํ์ผ ์ ์ฉ == > ํจ์์คํ์ผ๋ก ๋ง๋ค์ด๋ณด๊ธฐ
from openpyxl import Workbook
import random
from datetime import datetime, timedelta
from openpyxl.styles import Font, PatternFill, Alignment
def create_format_sample():
wb = Workbook()
ws = wb.active
headers = ['์ด๋ฆ','๋ถ์','์ง๊ธ','์
์ฌ์ผ','๊ธ์ฌ']
ws.append(headers)
sample_data = [
['๊น์ฒ ์','์์
๋ถ','๋๋ฆฌ','2020-01-01','3500000'],
['์ด์ํฌ','๊ฐ๋ฐํ','๊ณผ์ฅ','2018-03-15','4500000'],
['๋ฐ์ง์ฑ','์ธ์ฌํ','์ฌ์','2022-08-01','3000000'],
['์ต๋ฏผ์','์์
๋ถ','์ฐจ์ฅ','2015-12-01','5500000'],
['์ ์์ฐ','๊ฐ๋ฐํ','๋๋ฆฌ','2021-06-15','3800000']
]
for row in sample_data:
ws.append(row)
header_fill = PatternFill(start_color='DDDDDD', end_color='DDDDDD', fill_type='solid')
ws['A1'].fill = header_fill
ws['B1'].fill = header_fill
ws['C1'].fill = header_fill
ws['D1'].fill = header_fill
ws['E1'].fill = header_fill
## ํฐํธ ๋ณ๊ฒฝ
ft = Font(size=12, color='000000', bold=True, name='๋์')
ws['A1'].font = ft
ws['B1'].font = ft
ws['C1'].font = ft
ws['D1'].font = ft
ws['E1'].font = ft
## ์ ๋ ฌ ์ง์
alignment_type = Alignment(horizontal='center',vertical='center')
ws['A1'].alignment = alignment_type
ws['B1'].alignment = alignment_type
ws['C1'].alignment = alignment_type
ws['D1'].alignment = alignment_type
ws['E1'].alignment = alignment_type
wb.save('์์
์๋ํ/format_sample.xlsx')
wb.close()
create_format_sample()
Inย [145]:
from openpyxl import Workbook
import random
from datetime import datetime, timedelta
wb = Workbook()
ws = wb.active
ws.title = 'data'
ws.append(['์ํ์ฝ๋','์ํ๋ช
','์ฌ๊ณ ์๋','๋จ๊ฐ'])
products = ['๋
ธํธ๋ถ', 'ํ๋ธ๋ฆฟ', '์ค๋งํธํฐ', '๋ชจ๋ํฐ', 'ํค๋ณด๋', '๋ง์ฐ์ค']
for i in range(1,101):
# code = f"p{str(i).zfill(3)}"
code = f"P{i:03d}"
name = random.choice(products)
quantity = random.randint(10,1000)
price = random.randint(10000,2000000)
ws.append([code,name,quantity,price])
wb.save('์์
์๋ํ/code_data_sample.xlsx')
wb.close()
Inย [152]:
## ํํฐ๋ง
from openpyxl import Workbook, load_workbook
import win32com.client
import os
def filter_data(filename,x,y):
filter_wb = Workbook()
filter_ws = filter_wb.active
filter_ws.title = 'filter'
wb = load_workbook(filename, data_only=True)
ws = wb.active
for cell in ws[1]:
filter_ws[cell.coordinate] = cell.value # ํ์ฌ ์
์ขํ ('A1')
row_idx =2
for row in ws.iter_rows(min_row=2):
if row[x].value >= y:
for col_idx, cell in enumerate(row,1):
filter_ws.cell(row=row_idx,column=col_idx,value=cell.value)
row_idx += 1
filter_wb.save(f"์์
์๋ํ/filter_data.xlsx")
filter_wb.close()
filter_data('์์
์๋ํ/code_data_sample.xlsx',2,100)
Inย [153]:
from openpyxl import load_workbook, Workbook
from openpyxl.utils import column_index_from_string
def filter_data(input_file, column_letter, min_value):
wb = load_workbook(input_file)
ws = wb.active
new_wb = Workbook()
new_ws = new_wb.active
# ํค๋ ๋ณต์ฌ
for cell in ws[1]:
new_ws[cell.coordinate] = cell.value
# ์กฐ๊ฑด์ ๋ง๋ ๋ฐ์ดํฐ๋ง ํํฐ๋ง
column_index = column_index_from_string(column_letter) # ๋ฌธ์๋ก ๋ ์ด์ ์ธ๋ฑ์ค๋ก ๋ณํ
row_idx = 2
for row in ws.iter_rows(min_row=2):
if row[column_index - 1].value >= min_value: # ํน์ ์ด์ ๊ฐ์ด ๊ธฐ์ค๊ฐ ์ด์์ธ ๊ฒฝ์ฐ
for col_idx, cell in enumerate(row, start=1):
new_ws.cell(row=row_idx, column=col_idx, value=cell.value)
row_idx += 1
new_wb.save('์์
์๋ํ/filtered_data2.xlsx')
filter_data('์์
์๋ํ/code_data_sample.xlsx', 'C', 100)
Inย [ย ]:
from openpyxl import Workbook
def create_validation_sample():
wb = Workbook()
ws = wb.active
ํค๋ ์ถ๊ฐ
ws.append(['์ฃผ๋ฌธ๋ฒํธ', '๊ณ ๊ฐ๋ช
', '์ฃผ๋ฌธ๊ธ์ก', '์ฃผ๋ฌธ์ผ์'])
์ผ๋ถ๋ฌ ์ค๋ฅ๊ฐ ํฌํจ๋ ๋ฐ์ดํฐ ์์ฑ
sample_data = [
['ORD001', '๊น์ฒ ์', '50000', '2024-01-01'],
['ORD002', '', '60000', '2024-01-02'], # ๋น ๊ณ ๊ฐ๋ช
['ORD003', '๋ฐ์ง์ฑ', 'invalid', '2024-01-03'], # ์๋ชป๋ ๊ธ์ก
['ORD004', '์ด์ํฌ', '70000', ''], # ๋น ๋ ์ง
['ORD005', '์ต๋ฏผ์', '80000', '2024-01-05']
]
for row in sample_data:
ws.append(row)
wb.save('validation_sample.xlsx')
Inย [157]:
## ์๋ฌ ๋ฐ์ดํฐ ํ์
from openpyxl import load_workbook
def validate_data(filename):
wb = load_workbook(filename)
ws = wb.active
errors = []
for row_idx, row in enumerate(ws.iter_rows(min_row = 2),2):
# ๋น ์
ํ์ธ
for col_idx, cell in enumerate(row,1):
if cell.value is None:
errors.append(f"๋น ์
๋ฐ๊ฒฌ: {row_idx}ํ {col_idx}์ด")
try:
float(row[2].value)
except ValueError:
errors.append(f"์๋ชป๋ ์ซ์ ํ์: {row_idx}ํ")
if errors:
with open('validation_report.txt','w',encoding='utf-8') as f:
for error in errors:
f.write(f"{error}\n")
validate_data('์์
์๋ํ/validation_sample.xlsx')
Inย [158]:
from openpyxl import Workbook
import random
from datetime import datetime, timedelta
def create_chart_sample():
wb = Workbook()
ws = wb.active
# ํค๋ ์ถ๊ฐ
ws.append(['์', '๋งค์ถ์ก', '๋ชฉํ๋งค์ถ'])
# 2024๋
์๋ณ ๋ฐ์ดํฐ
for month in range(1, 13):
sales = random.randint(80000000, 150000000)
target = 100000000 # ๋ชฉํ๋งค์ถ 1์ต์ผ๋ก ๊ณ ์
ws.append([f'2024-{str(month).zfill(2)}', sales, target])
wb.save('chart_sample.xlsx')
create_chart_sample()
Inย [160]:
from openpyxl import load_workbook
from openpyxl.chart import BarChart, Reference
def create_chart(filename):
wb = load_workbook(filename)
ws = wb.active
# ์ฐจํธ ์์ฑ
chart = BarChart()
chart.title = "๋งค์ถ ํํฉ"
chart.x_axis.title = "๋ ์ง"
chart.y_axis.title = "๋งค์ถ์ก"
# ๋ฐ์ดํฐ ๋ฒ์ ์ค์
data = Reference(ws, min_col=2, min_row=1, max_row=ws.max_row)
cats = Reference(ws, min_col=1, min_row=2, max_row=ws.max_row)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
# ์ฐจํธ ํฌ๊ธฐ
chart.width = 500 (ํฌ์ธํธ)
chart.height = 400 (ํฌ์ธํธ)
# ์ฐจํธ ์ถ๊ฐ
ws.add_chart(chart, "E1")
wb.save('chart_report.xlsx')
create_chart('chart_sample.xlsx')
Inย [161]:
from openpyxl import load_workbook
from openpyxl.chart import (BarChart, LineChart, PieChart, ScatterChart,
Reference, Series)
def create_various_charts(filename):
wb = load_workbook(filename)
ws = wb.active
# "์ฐจํธ ๋ชจ์" ์ํธ ์์ฑ
chart_sheet = wb.create_sheet(title="์ฐจํธ ๋ชจ์")
# ๋ฐ์ดํฐ ๋ฒ์ ์ค์
data = Reference(ws, min_col=2, min_row=1, max_row=ws.max_row)
cats = Reference(ws, min_col=1, min_row=2, max_row=ws.max_row)
# 1. ์ธ๋ก ๋ง๋ ์ฐจํธ
bar_chart = BarChart()
bar_chart.title = "๋งค์ถ ํํฉ (์ธ๋ก ๋ง๋)"
bar_chart.x_axis.title = "๋ ์ง"
bar_chart.y_axis.title = "๋งค์ถ์ก"
bar_chart.add_data(data, titles_from_data=True)
bar_chart.set_categories(cats)
chart_sheet.add_chart(bar_chart, "A1")
# 2. ๊ฐ๋ก ๋ง๋ ์ฐจํธ
horizontal_bar = BarChart()
horizontal_bar.type = "bar"
horizontal_bar.title = "๋งค์ถ ํํฉ (๊ฐ๋ก ๋ง๋)"
horizontal_bar.x_axis.title = "๋งค์ถ์ก"
horizontal_bar.y_axis.title = "๋ ์ง"
horizontal_bar.add_data(data, titles_from_data=True)
horizontal_bar.set_categories(cats)
chart_sheet.add_chart(horizontal_bar, "A15")
# 3. ์ ๊ทธ๋ํ
line_chart = LineChart()
line_chart.title = "๋งค์ถ ์ถ์ด"
line_chart.x_axis.title = "๋ ์ง"
line_chart.y_axis.title = "๋งค์ถ์ก"
line_chart.add_data(data, titles_from_data=True)
line_chart.set_categories(cats)
line_chart.style = 10
chart_sheet.add_chart(line_chart, "I1")
# 4. ํ์ด ์ฐจํธ (์ฒซ 6๊ฐ ๋ฐ์ดํฐ๋ง)
pie_chart = PieChart()
pie_chart.title = "๋งค์ถ ๋น์ค (์์ 6๊ฐ)"
pie_data = Reference(ws, min_col=2, min_row=1, max_row=7)
pie_labels = Reference(ws, min_col=1, min_row=2, max_row=7)
pie_chart.add_data(pie_data, titles_from_data=True)
pie_chart.set_categories(pie_labels)
chart_sheet.add_chart(pie_chart, "I15")
# 5. ๋ณตํฉ ์ฐจํธ (๋งค์ถ vs ๋ชฉํ)
combo_chart = LineChart()
combo_chart.title = "๋งค์ถ vs ๋ชฉํ"
combo_chart.x_axis.title = "๋ ์ง"
combo_chart.y_axis.title = "๊ธ์ก"
sales_data = Reference(ws, min_col=2, min_row=1, max_row=ws.max_row)
target_data = Reference(ws, min_col=3, min_row=1, max_row=ws.max_row)
combo_chart.add_data(sales_data, titles_from_data=True)
combo_chart.add_data(target_data, titles_from_data=True)
combo_chart.set_categories(cats)
chart_sheet.add_chart(combo_chart, "Q1")
# 6. ๋ถ์ฐํ ์ฐจํธ
scatter_chart = ScatterChart()
scatter_chart.title = "๋งค์ถ-๋ชฉํ ์๊ด๊ด๊ณ"
scatter_chart.x_axis.title = "๋งค์ถ์ก"
scatter_chart.y_axis.title = "๋ชฉํ๋งค์ถ"
xvalues = Reference(ws, min_col=2, min_row=2, max_row=ws.max_row)
yvalues = Reference(ws, min_col=3, min_row=2, max_row=ws.max_row)
series = Series(yvalues, xvalues, title="๋งค์ถ vs ๋ชฉํ")
scatter_chart.series.append(series)
chart_sheet.add_chart(scatter_chart, "Q15")
# ์๋ณธ ์ํฌ์ํธ์๋ ์ฐจํธ ์ถ๊ฐ
# 1. ์ธ๋ก ๋ง๋ ์ฐจํธ (์๋ณธ์ฉ)
orig_bar_chart = BarChart()
orig_bar_chart.title = "๋งค์ถ ํํฉ (์ธ๋ก ๋ง๋)"
orig_bar_chart.x_axis.title = "๋ ์ง"
orig_bar_chart.y_axis.title = "๋งค์ถ์ก"
orig_bar_chart.add_data(data, titles_from_data=True)
orig_bar_chart.set_categories(cats)
ws.add_chart(orig_bar_chart, "E1")
wb.save('various_charts.xlsx')
# ํจ์ ์คํ
create_various_charts('chart_sample.xlsx')
Inย [ย ]: