python簡說(二十)操作excel
阿新 • • 發佈:2018-12-18
一.pip install xlrd
pip install xlwt
pip install xlutils
二.寫excel
import xlwt
book = xlwt.Workbook() #新建一個excel
sheet = book.add_sheet('sheet1') #新增一個sheet頁
row = 0 #行
for stu in stu_info:
#stu
col = 0 # 列
# [1, 'machunbo', 'sdfsd23sdfsdf2', '男', '北京'],
for s in stu: #控制列
sheet.write(row,col,s) #0 3 男
col+=1
row+=1
二.讀excel
import xlrd
book = xlrd.open_workbook('stu3.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) #列數
for row in range(1,sheet.nrows):
print(sheet.row_values(row))
三.修改excel
import xlrd
from xlutils import copy
#1、先開啟原來的excel
#2、複製一份
#3、在複製的excel上修改
#4、儲存
book = xlrd.open_workbook('stu3.xls')
new_book = copy.copy(book) #
sheet = new_book.get_sheet(0) #修改excel的時候,得用get_sheet()
sheet.write(0,0,'id')
sheet.write(0,3,'password')
new_book.save('stu3.xls')