python操作excel、讀寫修改。


導入xlwt模塊

第一、新建一個excel文件

 

1、新建一個excel
2、添加sheet頁
3、寫入內容
4、保存該excel

import xlwt


book = xlwt.Workbook()           #新建一個excel
sheet = book1.add_sheet('sheet1')#sheet
sheet.write(0,0,'姓名')          #行、列、寫入的內容
sheet.write(0,1,'年齡')
sheet.write(0,2,'性別')
book.save('stu.xls')             #結尾一定要用.xls

 

第二 修改excel文件

 import xlutils,xlrd


from xlutils import copy

book = xlrd.open_workbook('app_student.xls')
#先用xlrd打開一個excel

new_book = copy.copy(book)

#通過xlutis先復制一個excel

sheet=new_book.get_sheet(0)#獲取sheet頁 get_sheet(0)是xlutils模塊的方法。
# sheet.write(0,0,'編號')
# sheet.write(0,1,'名字')

lis = ['編號','名字','性別','年齡','地址','班級','手機號','金幣']
for col, filed in enumerate(lis):
    sheet.write(0, col, filed)

new_book.save('app_student.xls')#保存

enumerate(lis)

在循環的時候能同時得到lis的下標和元素 

在這里  col做為下標,filed做為元組來進行循環,然后得到結果在寫入到excel中。

第三、 讀取excel文件

 

import xlrd

book= xlrd.open_workbook('app_student.xls')
sheet = book.sheet_by_index(0)
print(sheet.cell(0,0).value)#指定sheet里面的行和列
print(sheet.cell(1,0).value)
print(sheet.row_values(0)) #獲取整行的數據
print(sheet.nrows)         #獲取所有的行數

for i in range(sheet.nrows):
    print(sheet.row_values(i))#循環獲取到每行的數據


print(sheet.ncols)#獲取所有的列數
print(sheet.col_values(0)) #第一列的內容


for i in range(sheet.ncols):
    print(sheet.col_values(i))#獲取所有的列的數據

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM