26.python操作Excel

写入Excel

import xlwt
book=xlwt.Workbook(encoding='utf-8')
sheet=book.add_sheet('xiangxin')
# 标题名
title=['姓名','班级','住址','手机号']
# 输入的内容
shuru=[
    ['bred','class1','mingdong',188109],
    ['shade','class2','gugong',3332],
    ['dd','class3','changcheng',6666]
]
# 写入表头
i=0
for j in title:
    sheet.write(0,i,j)
    i+=1
# 写入表内容
l=1
for d in shuru:
    c=0
    for dd in d:
        sheet.write(l,c,dd)
        c+=1
    l+=1
# 保存
book.save('嵌套循环.xls')

读取Excel

import xlrd
book=xlrd.open_workbook('嵌套循环.xls') # 打开要读取的Excel
sheet=book.sheet_by_name('xiangxin')    # 打开xiangxin页
rows=sheet.nrows    # xiangxin页里面的行数
columns=sheet.ncols # xiangxin页里面的列数
print('行数为:',rows)
print('列数为:',columns)
print(sheet.cell(1,2).value)    # 通过制定行和列去获取到单元格里的内容

row_data=sheet.row_values(2)    # 获取第三行的内容,返回的是一个列表
print(row_data)

for i in range(rows):
    print(sheet.row_values(i))  # 遍历所有行的数据,返回的是列表数据类型

修改Excel(用这种方法就可以将数据写入到原有的Excel文件中)

# 由于xlrd的读取效率是最高的,而xlutils.copy即可以写入,
# 也可以修改,所以推荐使用xlrd读取,然后用xlutils.copy来写入修改
from xlutils.copy import copy
import xlrd
import os

# 打开需要修改的Excel
book=xlrd.open_workbook('嵌套循环.xls')
# 复制一份并在新Excel里写入要修改的数据
new_book=copy(book)
sheet=new_book.get_sheet(0) # 获取第一张表
sheet.write(5,5,'xiangshange')
sheet.write(0,0,'xiangshange')
# 保存新表
new_book.save('嵌套循环.xls')
原文地址:https://www.cnblogs.com/ubuntu1987/p/11936124.html