Python之操作Excel


使用之前先導入三個模塊:

import xlwt  #只能寫Excel
import xlrd   #只能讀Excel
import xlutils  #修改Excel,在原來的基礎上修改

一、 寫Excel

import xlwt  #引入模塊
book = xlwt.Workbook()  #創建 excel
sheet = book.add_sheet('sheet1')     #創建sheet頁
sheet.write(0,0,'名字')   #編輯表頭
sheet.write(1,0,'王一')   #編輯內容
sheet.write(2,0,'王二')

sheet.write(0,1,'手機號')  #編輯表頭
sheet.write(1,1,'119')     #編輯內容
sheet.write(2,1,'110')

book.save("students.xls")  #保存下,xlsx也可以保存,但會打不開,使用wps可以打開,使用微軟的會打不開

#保存的時候,如果是微軟的office,后綴.xls
#
保存的時候,如果是wps .xls .xlsx都可以

 使用循環方式寫入內容:

#給定文件內容:
stus= [
    ['id', 'name', 'sex', 'age', 'addr', 'grade', 'phone', 'gold'],
    [314, '礦泉水', '', 18, '北京市昌平區', '摩羯座', '18317155663', 14405],
    [315, '礦泉水', '', 27, '上海', '摩羯座', '18317155664', 100],
    [5985, '礦泉水', '', 18, '北京市昌平區', '班級', '18513867663', 100]
]

#內容寫入Excel
book=xlrt.Workbook() #新建一個Excel
sheet=book.add_sheet('sheet1') #新建一個sheet頁

row = 0#行號
for stu in stus:#控制行
    col = 0#列號
    for field in stu:#控制列的
        sheet.write(row,col,field)
        col+=1 #列號
    row+=1

book.save('students.xls') #保存內容

 

二、讀Excel

import xlrd

book=xlrd.open_workbook('stu.xls') #打開Excel
sheet=book.sheet_by_index(0) #根據編號獲取sheet頁
#sheet=book.sheet_by_name('sheet1') #也可以根據sheet頁名字獲取sheet頁

print(sheet.nrows) #Excel里有多少行
print(sheet.ncols)  #Excel里有多少列

print(sheet.cell(0,0).value) #獲取到指定單元格的內容
print(sheet.cell(0,1).value) #獲取到指定單元格的內容

print(sheet.row_values(0))  #獲取到整行的內容
print(sheet.col_values(0))   #獲取到整列的內容

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

三、修改Excel

由於xlwt模塊只能寫一次,再重新打開Excel后會覆蓋原來的內容;而xlrd模塊只能讀,因此修改Excel就要使用xlutils模塊了

#import xlutils
import xlrd   #兩個模塊配合使用
from xlutils import copy
import os

book=xlrd.open_workbook('student.xls')
#先用xlrd打開一個Excel
new_book=copy.copy(book)
#然后用xlutils里面的copy功能,復制一個Excel

sheet=new_book.get_sheet(0) #獲取sheet頁,注意這里的sheet 頁是xlutils里的,只能用.get_sheet()的方法獲取了

sheet.write(0,0,'ID')

os.rename('student.xls','student_bak.xls') #先把之前的Excel改下名字,之前的內容不至於丟失

new_book.save('student.xls') #修改完內容后再保存成同名的Excel

 

 


任何付出都是值得的,會越來越好


免責聲明!

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



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