欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PYTHON如何讀取和寫入EXCEL里面的數(shù)據(jù)

 更新時間:2019年10月28日 10:01:09   作者:圓覺  
這篇文章主要介紹了PYTHON如何讀取和寫入EXCEL里面的數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

好久沒寫了,今天來說說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)文章

最新評論