溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python操作excel需要使用的模塊有哪些

發(fā)布時(shí)間:2020-08-13 13:47:27 來(lái)源:億速云 閱讀:135 作者:小新 欄目:編程語(yǔ)言

python操作excel需要使用的模塊有哪些?這個(gè)問(wèn)題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見(jiàn)到的。希望通過(guò)這個(gè)問(wèn)題能讓你收獲頗深。下面是小編給大家?guī)?lái)的參考內(nèi)容,讓我們一起來(lái)看看吧!

python操作excel需要使用的模塊有xlrd、xlwt、xlutils。對(duì)excel進(jìn)行讀、寫(xiě)、更新操作。操作excel時(shí)需要先導(dǎo)入這些模塊,demo如下:

excel-讀操作知識(shí)點(diǎn):

import xlrd
'''
讀取 excel的操作步驟如下:
1. 打開(kāi)excel,打開(kāi)的excel必須存在
2. 獲取sheet對(duì)象
3. 對(duì)excel進(jìn)行操作:
    獲取excel的總行數(shù)、總列數(shù)、讀取excel每一行的數(shù)據(jù)、讀取excel每一列的數(shù)據(jù)、獲取某個(gè)單元格的值
'''
#打開(kāi)excel,打開(kāi)的excel必須存在,返回book對(duì)象
book = xlrd.open_workbook('students.xlsx')
#通過(guò)索引獲取sheet對(duì)象
sheet = book.sheet_by_index(0)
#有多個(gè)sheet頁(yè)時(shí)可以通過(guò)sheet的名稱來(lái)獲取sheet對(duì)象
sheet1 = book.sheet_by_name('Sheet1')

#獲取excel的總行數(shù),
rows = sheet.nrows
#獲取excel的總列數(shù)
cols = sheet.ncols
#獲取excel第2行的數(shù)據(jù),返回結(jié)果為list:[2.0, 'b', 'women']
row_value = sheet.row_values(2)
#獲取excel第1列的數(shù)據(jù),返回結(jié)果為list:['name', 'a', 'b', 'c', 'd', 'e', 'f', 'g', '小白', '小黑']
col_values = sheet.col_values(1)
#獲取單元格第8行第1列的數(shù)據(jù),返回結(jié)果為text: text:'小白'
cell_value = sheet.cell(8, 1)
#將text類(lèi)型的結(jié)果轉(zhuǎn)換為str類(lèi)型:小白
cell_str = sheet.cell(8, 1).value

注意:獲取每行、每列、某個(gè)單元格的值時(shí),注意行、列的值要存在,否則會(huì)報(bào)錯(cuò):list index out of range

excel - 讀取excel小案例:

import xlrd
'''
讀取excel的數(shù)據(jù),讀取數(shù)據(jù)的列固定,循環(huán)讀取每行數(shù)據(jù),讀取后的數(shù)據(jù)格式如下:
[
{'name':xxx,'sex':xxx,'id':1},
{'name':xxx,'sex':xxx,'id':1},
.......
]
'''
def readExcel():
    try:
        #若輸入的excel不存在,則打開(kāi)excel報(bào)錯(cuò)
        book = xlrd.open_workbook('students.xlsx')
    except Exception as e:
        print('error msg:', e)
    else:
        sheet = book.sheet_by_index(0)
        #獲取excel的總行數(shù)
        rows = sheet.nrows
        stu_list = []
        #循環(huán)讀取每行數(shù)據(jù),第0行是表頭信息,所以從第1行讀取數(shù)據(jù)
        for row in range(1, rows):
            stu = {}
            #獲取第row行的第0列所有數(shù)據(jù)
            id = sheet.cell(row, 0).value
            name = sheet.cell(row, 1).value
            sex = sheet.cell(row, 2).value
            #將id、name、sex添加到字典,若元素不存在則新增,否則是更新操作
            stu['id'] = id
            stu['name'] = name
            stu['sex'] = sex
            stu_list.append(stu)
        print(stu_list)
if __name__ == '__main__':
    readExcel()

excel數(shù)據(jù)格式如下:

python操作excel需要使用的模塊有哪些

excel - 寫(xiě)操作知識(shí)點(diǎn):

import xlwt
'''
寫(xiě) excel的操作步驟如下:
1. 打開(kāi)excel,打開(kāi)不存在的excel,若打開(kāi)已存在的excel,進(jìn)行寫(xiě)操作,寫(xiě)入的數(shù)據(jù)會(huì)覆蓋以前的數(shù)據(jù)
2. 獲取sheet對(duì)象并指定sheet的名稱
3. 對(duì)excel進(jìn)行操作:
    寫(xiě)入excel、保存excel
'''
#打開(kāi)excel創(chuàng)建book對(duì)象
book = xlwt.Workbook()
#創(chuàng)建sheet指定sheet名稱
sheet = book.add_sheet('stu2')
#寫(xiě)入excel數(shù)據(jù),第n行第n列寫(xiě)入某個(gè)值,寫(xiě)入的數(shù)據(jù)類(lèi)型為str
sheet.write(0, 0, '編號(hào)')
sheet.write(0, 1, '姓名')
sheet.write(0, 2, '年齡')
#保存excel,保存的后綴必須是xls
book.save('studet.xls')

excel寫(xiě)入 新的excel后,數(shù)據(jù)格式如下:

python操作excel需要使用的模塊有哪些

excel操作 已存在的excel,進(jìn)行寫(xiě)操作后的 excel格式如下:

python操作excel需要使用的模塊有哪些

 ----> 

python操作excel需要使用的模塊有哪些

excel - 寫(xiě)excel小案例:

import xlwt
'''
將list數(shù)據(jù):
[{'name': '小白', 'id': 1.0, 'sex': '男'},
    {'name': '小花', 'id': 2.0, 'sex': '女'},
    {'name': '小黑', 'id': 3.0, 'sex': '男'},
     {'name': '小茹', 'id': 4.0, 'sex': '女'},
     {'name': '小小', 'id': 5.0, 'sex': '男'}]
寫(xiě)入excel,title信息為:編號(hào)、姓名、性別
'''
def writeExcel():
    book = xlwt.Workbook()
    sheet = book.add_sheet('stu')
    titles = ['編號(hào)', '姓名', '性別']
    #循環(huán)讀取titles的長(zhǎng)度,col的值為:0,1,2,并將title值寫(xiě)入excel
    for title_col in range(len(titles)):
        #title 寫(xiě)入excel的第0行的第col列,寫(xiě)入titles[col]值
        sheet.write(0, title_col, titles[title_col])
    students_list = [{'name': '小白', 'id': 1.0, 'sex': '男'},{'name': '小花', 'id': 2.0, 'sex': '女'},
    {'name': '小黑', 'id': 3.0, 'sex': '男'},{'name': '小茹', 'id': 4.0, 'sex': '女'},
    {'name': '小小', 'id': 5.0, 'sex': '男'}]
    for stu_row in range(len(students_list)):
        #循環(huán)讀取student_list的長(zhǎng)度,從0開(kāi)始,寫(xiě)入excel時(shí)從第1行開(kāi)始寫(xiě)入數(shù)據(jù)
        #寫(xiě)入excel的數(shù)據(jù)是從list里進(jìn)行取值,獲取list的每個(gè)元素,返回字典,然后通過(guò)字典的key獲取value
        sheet.write(stu_row+1, 0, students_list[stu_row]['id'])
        sheet.write(stu_row+1, 1, students_list[stu_row]['name'])
        sheet.write(stu_row+1, 2, students_list[stu_row]['sex'])
    book.save('student.xls')
    if __name__ == '__main__':
    writeExcel()

excel數(shù)據(jù)格式如下:

python操作excel需要使用的模塊有哪些

excel- 更新操作知識(shí)點(diǎn):

import xlrd
from xlutils.copy import copy
'''
更新excel操作:
1. 打開(kāi)excel,更新的excel必須存在
2. 復(fù)制一個(gè)新的excel,使用xlutils模塊中的copy方法
3. 更新excel內(nèi)的數(shù)據(jù)
4. 保存更新后的excel數(shù)據(jù),以前的excel數(shù)據(jù)不會(huì)更改
'''
from xlutils.copy import copy
#打開(kāi)excel
book = xlrd.open_workbook('student.xlsx')
#復(fù)制一個(gè)新的excel
new_book = copy(book)
#查看某個(gè)對(duì)象下的所有方法
#print(dir(new_book))
#獲取新excel的sheet對(duì)象
sheet = new_book.get_sheet(0)
#新增一列數(shù)據(jù)
sheet.write(0, 3, '更新')
#更新第4行第1列的值,將其修改為'郭靜',修改的數(shù)據(jù)類(lèi)型為str
sheet.write(4, 1, '郭靜')
#保存更改后的excel,以前的excel數(shù)據(jù)不更改
new_book.save('student.xls')

以上為excel簡(jiǎn)單操作~~~~

案例:

寫(xiě)一個(gè)函數(shù),傳入一個(gè)表名,然后把這個(gè)表里面所有的數(shù)據(jù)導(dǎo)出excel里面。

import pymysql
import xlwt
import hashlib
dic = {
    "host": '192.1xx.xx.x',
    'user': 'mysql_xx',
    'password': 'xxx@123',
    'port': 3306,
    'db': 'user_xx'
}
#mysql 操作
def op_mysql( sql, res_many=False):
    con = pymysql.connect(host=dic['host'], user=dic['user'], password=dic['password'], db=dic['db'], 
    port=dic['port'], charset='utf8', autocommit=True)
    cur = con.cursor(pymysql.cursors.DictCursor)
    cur.execute(sql)
    if res_many:
        res = cur.fetchall()
    else:
        res = cur.fetchone()
    cur.close()
    con.close()
    return res
# 查詢sql,將結(jié)果寫(xiě)入excel
def op_table(table_name):
    sql = 'select * from {0};'.format(table_name)
    res_data = op_mysql(sql, res_many=True)  #返回結(jié)果是list [{},{}]
    book = xlwt.Workbook()
    sheet = book.add_sheet('標(biāo)簽')
    for row, row_data in enumerate(res_data):
        for col, col_key in enumerate(row_data):   # 獲取下標(biāo)、字典key
            if row == 0:
                sheet.write(0, col, col_key)
            else:
                sheet.write(row, col, row_data[col_key])
    book.save('label_data.xls')
op_table('xxx_label')

 excel 插件效果:

python操作excel需要使用的模塊有哪些

感謝各位的閱讀!看完上述內(nèi)容,你們對(duì)python操作excel需要使用的模塊有哪些大概了解了嗎?希望文章內(nèi)容對(duì)大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI