Python Excel操作

# 写Excel
import xlwt
book = xlwt.Workbook() # 初始化一个workbook
sheet = book.add_sheet("sheet1") # 新建一个sheet
sheet.write(0,0,"id") # 写入单元格内容
sheet.write(0,1,"name")
sheet.write(1,0,"1")
sheet.write(1,1,"test")
book.save("students1.xls") # 保存Excel 微软的office 结尾用.xlsx打不开 用wps xls和xlsx都可以打开
# 读excel
import xlrd
book = xlrd.open_workbook("students.xls")
sheet = book.sheet_by_index(0)
# sheet = book.sheet_by_name("sheet1")
print(sheet.cell(0,0).value) #指定单元格
print(sheet.row_values(0)) #获取某一行的数据
print(sheet.col_values(0)) #获取某一列的数据
print(sheet.nrows) #总共有多少行
print(sheet.ncols) #总共有多少列
print(sheet.cell_value(0,0)) #获取单元格的值
# 修改excel
import xlrd
from xlutils import copy
book = xlrd.open_workbook("students.xls")
new_book = copy.copy(book)
sheet = new_book.get_sheet(0)
sheet.write(1,1,"mytest")
new_book.save("students.xls")
posted @ 2021-01-20 17:36  Mia妈妈加油呀  阅读(80)  评论(0)    收藏  举报