Python 操作excel

來源:互聯網
上載者:User

標籤:pos   rom   +=   from   開始   excel   取數   value   office   

python操作excel使用xlrd、xlwt和xlutils模組。xlrd模組是讀取excel的,xlwt模組是寫excel的,xlutils是用來修改excel的

一、python  讀取excel

import xlrd
book = xlrd.open_workbook(‘all_stu.xls‘) #開啟一個excel
sheet = book.sheet_by_index(0) #根據順序擷取sheet
# sheet2 = book.sheet_by_name(‘sheet1‘) #根據sheet頁名字擷取sheet
# print(sheet.cell(0,0).value) #指定行和列擷取資料
# print(sheet.ncols) #擷取excel裡面有多少列
# print(sheet.nrows) #擷取excel裡面有多少行
sheet.row_values(1)#取第幾行的資料
# print(sheet.col_values(1)) #取第幾列的資料
for i in range(sheet.nrows): # 擷取excel中有多少行
print(sheet.row_values(i)) #取第幾行的資料

二、python 操作excel

import xlwt
stus = [
[‘姓名‘,‘年齡‘,‘性別‘,‘分數‘],
[‘mary‘, 20, ‘女‘, 89.9],
[‘mary‘, 20, ‘女‘, 89.9],
[‘mary‘, 20, ‘女‘, 89.9],
[‘mary‘, 20, ‘女‘, 89.9]
]
book = xlwt.Workbook() #建立一個excel
sheet = book.add_sheet(‘sheet1‘) #添加一個sheet頁
sheet.write(0,0,‘姓名‘)#一行一行寫入
# sheet.write(0,1,‘性別‘)
# sheet.write(0,2,‘年齡‘)
# book.save(‘stu.xls‘) #微軟的office不能用xlsx結尾的,wps隨意
raw = 0#控制行的
for stu in stus:#迴圈寫入
col = 0 #控制列 ,沒迴圈一次都從第一列開始寫入
for s in stu:
sheet.write(raw,col,s)
col+=1
raw+=1
book.save(‘kkk.xls‘)#微軟的office不能用xlsx結尾的,wps隨意

三、python 修改excel

from xlutils.copy import copy
import xlrd
book1 = xlrd.open_workbook(‘stu.xls‘)
book2 = copy(book1) #拷貝一份原來的excel
sheet = book2.get_sheet(0) #擷取第幾個sheet頁
sheet.write(1,3,0)#寫入需要修改的行、列及修改後的值
sheet.write(1,0,‘小黑‘)
book2.save(‘stu.xls‘)

 

Python 操作excel

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.