6)获取某个格子的行数、列数、坐标
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(sheet) cell1 = sheet["A1"] cell2 = sheet["C11"] print(cell1.value, cell1.row, cell1.column, cell1.coordinate) print(cell2.value, cell2.row, cell2.column, cell2.coordinate) """ .row 获取某个格子的行数; .columns 获取某个格子的列数; .corordinate 获取某个格子的坐标; """
结果如下:
7)获取一系列格子
① sheet[]方式
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(sheet) # 获取A1:C2区域的值 cell = sheet["A1:C2"] print(cell) for i in cell: for j in i: print(j.value)
结果如下:
特别的:如果我们只想获取“A列”,或者获取“A-C列”,可以采取如下方式:
sheet["A"] --- 获取A列的数据 sheet["A:C"] --- 获取A,B,C三列的数据 sheet[5] --- 只获取第5行的数据
② .iter_rows()方式
当然有.iter_rows()方式,肯定也会有.iter_cols()方式,只不过一个是按行读取,一个是按列读取。
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(sheet) # 按行获取值 for i in sheet.iter_rows(min_row=2, max_row=5, min_col=1, max_col=2): for j in i: print(j.value) # 按列获取值 for i in sheet.iter_cols(min_row=2, max_row=5, min_col=1, max_col=2): for j in i: print(j.value)
结果如下:
③ sheet.rows()
帮助我们获取所有行
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(sheet) for i in sheet.rows: print(i)
结果如下:
3、python如何向excel中写入某些内容?
1)修改表格中的内容
① 向某个格子中写入内容并保存
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(sheet) sheet["A1"] = "哈喽" # 这句代码也可以改为cell = sheet["A1"] cell.value = "哈喽" workbook.save(filename = "哈喽.xlsx") """ 注意:我们将“A1”单元格的数据改为了“哈喽”,并另存为了“哈喽.xlsx”文件。 如果我们保存的时候,不修改表名,相当于直接修改源文件; """
结果如下:
② .append():向表格中插入行数据
.append()方式:会在表格已有的数据后面,增添这些数(按行插入);
这个操作很有用,爬虫得到的数据,可以使用该方式保存成Excel文件;
workbook = load_workbook(filename = "test.xlsx") sheet = workbook.active print(sheet) data = [ ["唐僧","男","180cm"], ["孙悟空","男","188cm"], ["猪八戒","男","175cm"], ["沙僧","男","176cm"], ] for row in data: sheet.append(row) workbook.save(filename = "test.xlsx")
结果如下: