Python: Excel數據的讀寫操作

模塊的安裝

利用Python處理excel格式數據文件需要安裝xlrd模塊

pip install xlrd
pip install xlsxwriter

數據的讀取

import xlrd
#打開excle數據文件
xl = xlrd.open_workbook(r'./data.xlsx')

#通過索引獲取工作表
table = xl.sheets()[0]
print(table)
 
# 獲取行數
rows = table.nrows
print(rows)
cols = table.ncols
print(cols) 

# 獲取第一行的內容,索引從0開始
row = table.row_values(0)
print(row) #列表
# 獲取第一列的整列的內容,索引從0開始
col = table.col_values(0)
print(col) #列表
#獲取單元格值,第幾行第幾列,索引從0開始
data = table.cell(3,0).value
print(data)

數據的寫入

import xlsxwriter
#創建excel文件
xl = xlsxwriter.Workbook(r'./test.xlsx')

#添加sheet
sheet = xl.add_worksheet('sheet1')

#往單元格cell添加數據,索引寫入
sheet.write_string(0,0,'username')
#位置寫入
sheet.write_string('B1','password')
#設置單元格寬度大小
sheet.set_column('A:B',30)
#關閉文件
xl.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章