PYTHON如何讀取和寫入EXCEL里面的數(shù)據(jù)
好久沒寫了,今天來說說python讀取excel的常見方法。首先需要用到xlrd模塊,pip install xlrd 安裝模塊。
首先打開excel文件:
xl = xlrd.open_workbook(r'D:\file\data.xlsx') 傳文件路徑
通過索引獲取要操作的工作表
table = xl.sheets()[0]
有些人不知道啥是工作表,下圖這個:
獲取第一行的內(nèi)容,索引從0開始
row = table.row_values(0)
獲取第一列的整列的內(nèi)容
col = table.col_values(0)
獲取第一列,第0~4行(不含第4行)
print(table.col_values(0,0,4))
獲取單元格值,第幾行第幾個,索引從0開始
data = table.cell(2,0).value
pycharm讀取數(shù)據(jù)后發(fā)現(xiàn)整數(shù)變成了小數(shù)
如圖,手機號變小數(shù):
解決辦法:在整數(shù)內(nèi)容前加上一個英文的引號即可
讀取excel內(nèi)容方法截圖:
# todo 對excel的操作 import xlrd # todo 打開excle xl = xlrd.open_workbook(r'D:\file\data.xlsx') #print(xl.read()) # todo 通過索引獲取工作表 table = xl.sheets()[0] print(table) # 獲取一共多少行 rows = table.nrows print(rows) # todo 獲取第一行的內(nèi)容,索引從0開始 row = table.row_values(0) print(row) # todo 獲取第一列的整列的內(nèi)容 col = table.col_values(0) print(col) # todo 獲取單元格值,第幾行第幾個,索引從0開始 data = table.cell(3,0).value print(data)
寫入數(shù)據(jù)到excel的操作:
'''寫入excel文件''' import xlsxwriter # todo 創(chuàng)建excel文件 xl = xlsxwriter.Workbook(r'D:\testfile\test.xlsx') # todo 添加sheet sheet = xl.add_worksheet('sheet1') # todo 往單元格cell添加數(shù)據(jù),索引寫入 sheet.write_string(0,0,'username') # todo 位置寫入 sheet.write_string('B1','password') # todo 設(shè)置單元格寬度大小 sheet.set_column('A:B',30) # todo 關(guān)閉文件 xl.close()
方法截圖:
封裝讀取excel的方法:
import xlrd def config_data(): # 公共參數(shù) xl = xlrd.open_workbook(r'D:\testfile\config.xlsx') table = xl.sheets()[0] # todo 獲取單元行的內(nèi)容,索引取值 row = table.row_values(0) return row
測試是否可用:
'''測試data里面的配置數(shù)據(jù)是否可用''' from App_automation.data import config_data row = config_data() print(row[0])
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用TensorFlow創(chuàng)建生成式對抗網(wǎng)絡(luò)GAN案例
這篇文章主要為大家介紹了使用TensorFlow創(chuàng)建生成式對抗網(wǎng)絡(luò)GAN案例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03Django在Win7下的安裝及創(chuàng)建項目hello word簡明教程
這篇文章主要介紹了Django在Win7下的安裝及創(chuàng)建項目hello word,需要的朋友可以參考下2014-07-07python PyQt5對象類型的判定及對象刪除操作詳細(xì)解讀
PyQt5主要是用來判定一個對象的類型,或者說是否繼承自某個類,本文給大家介紹python PyQt5對象類型的判定,對象刪除操作詳細(xì)解讀,感興趣的朋友一起看看吧2024-07-07