Python如何讀取和寫入Excel數(shù)據(jù)

這篇文章主要介紹“Python如何讀取和寫入Excel數(shù)據(jù)”,在日常操作中,相信很多人在Python如何讀取和寫入Excel數(shù)據(jù)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Python如何讀取和寫入Excel數(shù)據(jù)”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

成都創(chuàng)新互聯(lián)服務項目包括科爾沁網(wǎng)站建設、科爾沁網(wǎng)站制作、科爾沁網(wǎng)頁制作以及科爾沁網(wǎng)絡營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關系等,向廣大中小型企業(yè)、政府機構等提供互聯(lián)網(wǎng)行業(yè)的解決方案,科爾沁網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟效益。目前,我們服務的客戶以成都為中心已經(jīng)輻射到科爾沁省份的部分城市,未來相信會繼續(xù)擴大服務區(qū)域并繼續(xù)獲得客戶的支持與信任!

使用python來操作Excel需要用到xlrd和xlwt這兩個庫,作用是在python中讀取和寫入excel數(shù)據(jù),使用前需要安裝和import導入;

1.Python 讀 excel數(shù)據(jù)

  • 使用Python 讀 excel數(shù)據(jù),首先需要使用xlrd.open_workbook(文件名)來打開Excel文件,默認是rb方式打開;

  • 然后可以通過xlrd庫對象中的方法來獲取Excel文件信息,讀取excel數(shù)據(jù);

import xlrd
from pprint import pprint
staff_excel = xlrd.open_workbook('./staff.xlsx')
# 獲取這個表中,sheet工作簿的名稱
print(staff_excel.sheet_names())
# 通過名字拿到對應的工作簿
sheet = staff_excel.sheet_by_name('員工基本信息')
# 顯示表格的行數(shù),和列數(shù)
print(sheet.nrows)
print(sheet.ncols)
# 讀取第二行的所有cell中的內(nèi)容
print(sheet.row_values(2))
# 獲取第2行,第0列的值
print(sheet.cell(2,0).value)
print(sheet.cell_value(2,0))
data_type = sheet.cell(2,2).ctype
print(data_type)
if data_type is 3:
    # 返回一個元組
    # ret = xlrd.xldate_as_tuple(sheet.cell_value(1,2),staff_excel.datemode)
    # 將excel表中時間轉(zhuǎn)換為python中的時間
    ret = xlrd.xldate_as_datetime(sheet.cell_value(1,2), staff_excel.datemode)  
    print(ret.strftime('%Y-%m-%d'))
  • row_values(i)col_values(i)方法可以獲取指定行數(shù)或者列數(shù)的信息,其中i是從0開始計數(shù)的,這兩個方法都是返回list對象

    • cell_value(i, j)方法可以讀取單元格數(shù)據(jù),i是行數(shù),j是列數(shù),行數(shù)和列數(shù)都是從0開始計數(shù)

  • 在excel中0表示empty,1表示string,2表示number,3表示date,4表示boolean,5表示error

2.將Excel數(shù)據(jù)轉(zhuǎn)換為json寫入到文件

  • 首先需要打開excel文件,然后通過名字拿到對應sheet,然后就可以開始操作excel表格;

  • 先創(chuàng)建一個空列表,獲取excel表格中的第一行作為字典的key值;
    然后在局部變量中創(chuàng)建一個字典對象(每次新的循環(huán),字典對象需求清空),通過兩層循環(huán)(外循環(huán)控制行,內(nèi)循環(huán)控制列)進行取值,將取到的值賦值給字典對象,每次循環(huán)完畢都將字典對象添加到定義的空列表中;
    要將數(shù)據(jù)寫入文件中,可以使用with上下文管理器,通過json.dumps()方法將之前存放數(shù)據(jù)的自定義列表進行序列化,然后寫入文件,想輸出真正的中文需要指定參數(shù)ensure_ascii=False

json_list = []
keys = sheet.row_values(0)
print(keys)
for index_r in range(1,sheet.nrows): # [1,2]
    # 這個字典必須是局部變量
    line = {}
    for index_c in range(sheet.ncols): # [0, 3]
        # 拿到類型
        cell_type = sheet.cell(index_r, index_c).ctype
        # 拿到值
        cell_value = sheet.cell(index_r, index_c).value
        # 如果是時間類型
        if cell_type is 3:
            cell_value = xlrd.xldate_as_datetime(cell_value, staff_excel.datemode).strftime('%Y-%m-%d')
        line[keys[index_c]] = cell_value
    else:
        json_list.append(line)
pprint(json_list, indent=4)
with open('staff.json', 'a+',) as f:
    f.write(json.dumps(json_list, ensure_ascii=False))

3.將json文件重新寫入Excel

# 創(chuàng)建一個Excel對象文件
new_staff = xlwt.Workbook()
staff_sheet = new_staff.add_sheet('xkd員工信息')
with open('staff.json') as f:
    # 返回一個列表
    data = json.load(f)
# 獲取Excel中的第一行
item = data[0]
# 獲取Excel中的值
column_values = []
for item in data:
    column_values.append(item.values())
# 寫入第一行
for i,key in enumerate(item.keys()):
    print(key)
    staff_sheet.write(0, i, label=key)
# 寫入其他的行
for i,column in enumerate(column_values):
    for j,column_value in enumerate(column):
        staff_sheet.write(i+1, j, label=column_value)
new_staff.save('./new_staff.xls')

到此,關于“Python如何讀取和寫入Excel數(shù)據(jù)”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

本文題目:Python如何讀取和寫入Excel數(shù)據(jù)
轉(zhuǎn)載源于:http://www.muchs.cn/article18/jpjpgp.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供微信公眾號、用戶體驗、品牌網(wǎng)站設計、微信小程序做網(wǎng)站、外貿(mào)網(wǎng)站建設

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站