一直看到有用python进行自动化办公的视频,但没有去学习过,正好yby找我帮忙处理一个excel文件,借此机会简单学习一下,简单了解之后发现不是很难,都有现成的库来支持。
用到的库
基本操作
打开文件
book = xlrd.open_workbook('input.xls')
sheet1 = book.sheet_by_index(0)
|
读取文件
在xlrd中读取excel表格中的指定行列有三种方法:
row_1 = sheet1.row(1).value pos_1_0 =sheet1.row(1)[0].value
|
col_1 = sheet1.col(1).value pos_0_1 =sheet1.col(1)[0].value
|
pos_1_0 = sheet1.cell(1, 0).value
|
简单示例
代码示例
import xlrd
sheet1 = xlrd.open_workbook('123.xls').sheet_by_index(0)
output = open('output.txt', 'w', encoding='utf-8')
for i in range(1, sheet1.nrows): if sheet1.row(i)[0].value in [1, 2]: output.write(f'{sheet1.row(i)[1].value}:{sheet1.row(i)[2].value}\n') output.write(f'答案:{str(sheet1.row(i)[3].value)}\n') output.write(f'A: {sheet1.row(i)[4].value}\n') output.write(f'B: {sheet1.row(i)[5].value}\n') output.write(f'C: {sheet1.row(i)[6].value}\n') output.write(f'D: {sheet1.row(i)[7].value}\n') output.write(f'E: {sheet1.row(i)[8].value}\n') if sheet1.row(i)[0].value == 3: output.write(f'{sheet1.row(i)[1].value}:{sheet1.row(i)[2].value}\n') output.write(f'答案:{str(sheet1.row(i)[3].value)}\n') output.close()
|
运行结果

