In [1]:
import openpyxl
import pprint
In [2]:
wb = openpyxl.load_workbook('data/src/sample.xlsx')
In [3]:
print(type(wb))
In [4]:
print(wb.sheetnames)
In [5]:
sheet = wb['sheet1']
In [6]:
print(type(sheet))
In [7]:
cell = sheet['A2']
In [8]:
print(type(cell))
In [9]:
print(cell.value)
In [10]:
cell = sheet.cell(row=2, column=1)
In [11]:
print(type(cell))
In [12]:
print(cell.value)
In [13]:
pprint.pprint(sheet['A2:C4'])
In [14]:
g = sheet.iter_rows(min_row=2, max_row=4, min_col=1, max_col=3)
In [15]:
print(type(g))
In [16]:
pprint.pprint(list(g))
In [17]:
def get_value_list(t_2d):
return([[cell.value for cell in row] for row in t_2d])
In [18]:
l_2d = get_value_list(sheet['A2:C4'])
pprint.pprint(l_2d, width=40)
In [19]:
def get_list_2d(sheet, start_row, end_row, start_col, end_col):
return get_value_list(sheet.iter_rows(min_row=start_row,
max_row=end_row,
min_col=start_col,
max_col=end_col))
In [20]:
l_2d = get_list_2d(sheet, 2, 4, 1, 3)
pprint.pprint(l_2d, width=40)
In [21]:
g_all = sheet.values
print(type(g_all))
In [22]:
pprint.pprint(list(g_all), width=40)
In [23]:
sheet['C1'] = 'XXX'
sheet['E1'] = 'new'
In [24]:
pprint.pprint(list(sheet.values), width=40)
In [25]:
sheet.cell(row=2, column=5, value=14)
pprint.pprint(list(sheet.values), width=40)
In [26]:
def write_list_2d(sheet, l_2d, start_row, start_col):
for y, row in enumerate(l_2d):
for x, cell in enumerate(row):
sheet.cell(row=start_row + y,
column=start_col + x,
value=l_2d[y][x])
In [27]:
l_2d = [['four', 41, 42, 43], ['five', 51, 52, 53]]
write_list_2d(sheet, l_2d, 5, 1)
In [28]:
pprint.pprint(list(sheet.values), width=40)
In [29]:
sheet_new = wb.create_sheet('sheet_new')
print(wb.worksheets)
In [30]:
sheet_new['A1'] = 'new sheet!'
print(list(sheet_new.values))
In [31]:
sheet_copy = wb.copy_worksheet(wb['sheet1'])
In [32]:
print(wb.worksheets)
In [33]:
pprint.pprint(list(sheet_copy.values))
In [34]:
wb.remove_sheet(wb['sheet1 Copy'])
In [35]:
print(wb.worksheets)
In [36]:
wb.save('data/dst/openpyxl_sample.xlsx')