python学习——操作excel

python操作excel使用xlrd、xlwt模块,xlrd模块是读取excel的,xlwt模块是写excel的。这几个模块可以使用pip安装,

pip install xlrd

pip install xlwt

1、参考代码:

# import xlrd
import xlwt


# file_path = "C:\\Users\\yl8\\Desktop\\测试用例-V1.2.0_完整版.xlsx"
# # 打开一个excel表,打开的这个表必须存在,否则会报错
# wb = xlrd.open_workbook(file_path)
# # 获取所有sheet页的名字
# print(wb.sheet_names())
# # 根据sheet页的索引获取sheet页
# print(wb.sheet_names()[1])
# sheet = wb.sheet_by_index(0)
# sheet1 = wb.sheet_by_name('总平台')
# print(sheet1.nrows)   # 获取sheet页的行数
# print(sheet1.ncols)    # 获取sheet页的列数
# print(sheet1.row_values(3))   # 根据sheet名称获取整行的值
# print(sheet1.col_values(2))   # 根据sheet名称获取整列的值
# print(sheet1.cell(3,1).value)    # 获取指定单元格内容的数据类型
#
# # 打印每行的信息
# for rownum in range(sheet.nrows):     # 循环取每行的数据
#     print(sheet1.row_values(rownum))   # 取每行的数据
# # 按照索引打印对应单元格内容
# cell_A2 = sheet.cell(2,1).value
# # print(cell_A2)
book = xlwt.Workbook()      # 新建一个Excel对象
sheet = book.add_sheet('sheet1')    # 添加一个指定名称的sheet页
stus = [
    ['id','name','sex','age','address','grade'],
    [315,'张三','',16,'北京市海淀区',98],
    [314,'李四','','22','陕西省西安市',99]
]

def save_stu(stu):
    for row,stu in enumerate(stus):
        for col,fielf in enumerate(stu):
            sheet.write(row,col,fielf)

    book.save('students.xls')


save_stu(stus)

猜你喜欢

转载自www.cnblogs.com/yuer02/p/12672668.html