python操作excel需要使用的模塊有哪些?這個問題可能是我們日常學習或工作經常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家帶來的參考內容,讓我們一起來看看吧!
python操作excel需要使用的模塊有xlrd、xlwt、xlutils。對excel進行讀、寫、更新操作。操作excel時需要先導入這些模塊,demo如下:
excel-讀操作知識點:
import xlrd
'''
讀取 excel的操作步驟如下:
1. 打開excel,打開的excel必須存在
2. 獲取sheet對象
3. 對excel進行操作:
獲取excel的總行數、總列數、讀取excel每一行的數據、讀取excel每一列的數據、獲取某個單元格的值
'''
#打開excel,打開的excel必須存在,返回book對象
book = xlrd.open_workbook('students.xlsx')
#通過索引獲取sheet對象
sheet = book.sheet_by_index(0)
#有多個sheet頁時可以通過sheet的名稱來獲取sheet對象
sheet1 = book.sheet_by_name('Sheet1')
#獲取excel的總行數,
rows = sheet.nrows
#獲取excel的總列數
cols = sheet.ncols
#獲取excel第2行的數據,返回結果為list:[2.0, 'b', 'women']
row_value = sheet.row_values(2)
#獲取excel第1列的數據,返回結果為list:['name', 'a', 'b', 'c', 'd', 'e', 'f', 'g', '小白', '小黑']
col_values = sheet.col_values(1)
#獲取單元格第8行第1列的數據,返回結果為text: text:'小白'
cell_value = sheet.cell(8, 1)
#將text類型的結果轉換為str類型:小白
cell_str = sheet.cell(8, 1).value注意:獲取每行、每列、某個單元格的值時,注意行、列的值要存在,否則會報錯:list index out of range
excel - 讀取excel小案例:
import xlrd
'''
讀取excel的數據,讀取數據的列固定,循環讀取每行數據,讀取后的數據格式如下:
[
{'name':xxx,'sex':xxx,'id':1},
{'name':xxx,'sex':xxx,'id':1},
.......
]
'''
def readExcel():
try:
#若輸入的excel不存在,則打開excel報錯
book = xlrd.open_workbook('students.xlsx')
except Exception as e:
print('error msg:', e)
else:
sheet = book.sheet_by_index(0)
#獲取excel的總行數
rows = sheet.nrows
stu_list = []
#循環讀取每行數據,第0行是表頭信息,所以從第1行讀取數據
for row in range(1, rows):
stu = {}
#獲取第row行的第0列所有數據
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數據格式如下:

excel - 寫操作知識點:
import xlwt
'''
寫 excel的操作步驟如下:
1. 打開excel,打開不存在的excel,若打開已存在的excel,進行寫操作,寫入的數據會覆蓋以前的數據
2. 獲取sheet對象并指定sheet的名稱
3. 對excel進行操作:
寫入excel、保存excel
'''
#打開excel創建book對象
book = xlwt.Workbook()
#創建sheet指定sheet名稱
sheet = book.add_sheet('stu2')
#寫入excel數據,第n行第n列寫入某個值,寫入的數據類型為str
sheet.write(0, 0, '編號')
sheet.write(0, 1, '姓名')
sheet.write(0, 2, '年齡')
#保存excel,保存的后綴必須是xls
book.save('studet.xls')excel寫入 新的excel后,數據格式如下:

excel操作 已存在的excel,進行寫操作后的 excel格式如下:

---->

excel - 寫excel小案例:
import xlwt
'''
將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': '男'}]
寫入excel,title信息為:編號、姓名、性別
'''
def writeExcel():
book = xlwt.Workbook()
sheet = book.add_sheet('stu')
titles = ['編號', '姓名', '性別']
#循環讀取titles的長度,col的值為:0,1,2,并將title值寫入excel
for title_col in range(len(titles)):
#title 寫入excel的第0行的第col列,寫入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)):
#循環讀取student_list的長度,從0開始,寫入excel時從第1行開始寫入數據
#寫入excel的數據是從list里進行取值,獲取list的每個元素,返回字典,然后通過字典的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數據格式如下:

excel- 更新操作知識點:
import xlrd
from xlutils.copy import copy
'''
更新excel操作:
1. 打開excel,更新的excel必須存在
2. 復制一個新的excel,使用xlutils模塊中的copy方法
3. 更新excel內的數據
4. 保存更新后的excel數據,以前的excel數據不會更改
'''
from xlutils.copy import copy
#打開excel
book = xlrd.open_workbook('student.xlsx')
#復制一個新的excel
new_book = copy(book)
#查看某個對象下的所有方法
#print(dir(new_book))
#獲取新excel的sheet對象
sheet = new_book.get_sheet(0)
#新增一列數據
sheet.write(0, 3, '更新')
#更新第4行第1列的值,將其修改為'郭靜',修改的數據類型為str
sheet.write(4, 1, '郭靜')
#保存更改后的excel,以前的excel數據不更改
new_book.save('student.xls')以上為excel簡單操作~~~~
案例:
寫一個函數,傳入一個表名,然后把這個表里面所有的數據導出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,將結果寫入excel def op_table(table_name): sql = 'select * from {0};'.format(table_name) res_data = op_mysql(sql, res_many=True) #返回結果是list [{},{}] book = xlwt.Workbook() sheet = book.add_sheet('標簽') for row, row_data in enumerate(res_data): for col, col_key in enumerate(row_data): # 獲取下標、字典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需要使用的模塊有哪些大概了解了嗎?希望文章內容對大家有所幫助。如果想了解更多相關文章內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。