from openpyxl import Workbook
wb = Workbook()
print(wb.active)
sheet = wb.active
sheet.title = "fangchen1"
wb.save("excelTest.xlsx")
wb = Workbook() Create a... In memory excel form
wb.active This is the highlighted
This table is assigned to sheet
then sheet.title = "fangchen1" It's called fangchen1
wb.save("excelTest.xlsx") Note that the previous is created in memory , Only save Then it will be put on the disk , It is equivalent to saving as . Then you will find that there is a in the current directory excelTest.xlsx The file of
Cell operation traversal
1. open excel form
from openpyxl import load_workbook
wb = load_workbook("excelTest.xlsx")
2. Pick that sheet
print(wb.sheetnames)
#sheet = wb.get_sheet_by_name("Sheet1")
sheet = wb["Sheet1"]
print After that sheet The name of
The second line of code can be selected sheet, however python It seems that... Is not recommended , A warning message appears
Use the third line to select sheet, By name
The following code is to operate on a cell , assignment , Print , Note that the second and third lines print different things
sheet["B3"] = "fangchen"
print(sheet["B3"])
print(sheet["B3"].value)
Traverse selected cells
# Print from A1:A10 Cell data
for cell in sheet["A1:A10"]:
cell[0].value = "fangchen"
print(cell[0].value)
Traverse the entire table
for row in sheet:
for cell in row:
print(cell.value,end=",")
print()
The second line to the fifth line , Print five per line
for row in sheet.iter_rows(min_row = 2,max_row = 5,max_col = 5):
for cell in row:
cell.value = "chengyichen"
Loop through by column
# Cycle by column
for col in sheet.columns:
for cell in col:
print(cell.value,end=',')
print()
Print the specified column , Just learned python, Not very much , Try this max_col and min_col You can change places , But don't type the wrong name . And that iter_cols No wrong number
for col in sheet.iter_cols(max_col = 3,min_col = 1,max_row = 5):
for cell in col:
print(cell.value)
Delete cells
for col in sheet.iter_cols(max_col = 3,min_col = 1,min_row = 1,max_row = 5):
for cell in col:
print(cell.value)
wb.remove(sheet)
then , Did the above , All are done in memory , If you don't write it back to the disk, it won't be saved .
1、opencc-python First introduc