1. 程式人生 > 程式設計 >PYTHON如何讀取和寫入EXCEL裡面的資料

PYTHON如何讀取和寫入EXCEL裡面的資料

好久沒寫了,今天來說說python讀取excel的常見方法。首先需要用到xlrd模組,pip install xlrd 安裝模組。

首先開啟excel檔案:

xl = xlrd.open_workbook(r'D:\file\data.xlsx') 傳檔案路徑

通過索引獲取要操作的工作表

table = xl.sheets()[0]

有些人不知道啥是工作表,下圖這個:

獲取第一行的內容,索引從0開始

row = table.row_values(0)

獲取第一列的整列的內容

col = table.col_values(0)

獲取第一列,第0~4行(不含第4行)

print(table.col_values(0,4))

獲取單元格值,第幾行第幾個,索引從0開始

data = table.cell(2,0).value

pycharm讀取資料後發現整數變成了小數

如圖,手機號變小數:

解決辦法:在整數內容前加上一個英文的引號即可

讀取excel內容方法截圖:

# 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 獲取第一行的內容,索引從0開始
row = table.row_values(0)
print(row)

# todo 獲取第一列的整列的內容
col = table.col_values(0)
print(col)

# todo 獲取單元格值,第幾行第幾個,索引從0開始
data = table.cell(3,0).value
print(data)

寫入資料到excel的操作:

'''寫入excel檔案'''
import xlsxwriter

# todo 建立excel檔案
xl = xlsxwriter.Workbook(r'D:\testfile\test.xlsx')

# todo 新增sheet
sheet = xl.add_worksheet('sheet1')

# todo 往單元格cell新增資料,索引寫入
sheet.write_string(0,'username')

# todo 位置寫入
sheet.write_string('B1','password')

# todo 設定單元格寬度大小
sheet.set_column('A:B',30)

# todo 關閉檔案
xl.close()

方法截圖:

封裝讀取excel的方法:

import xlrd
def config_data():
  # 公共引數
  xl = xlrd.open_workbook(r'D:\testfile\config.xlsx')
  table = xl.sheets()[0]
  # todo 獲取單元行的內容,索引取值
  row = table.row_values(0)
  return row

測試是否可用:

'''測試data裡面的配置資料是否可用'''
from App_automation.data import config_data
row = config_data()
print(row[0])

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。