python excel讀寫與dict轉換

2021-08-21 07:24:21 字數 2639 閱讀 7474

學習excel讀寫,將乙個excel檔案內容轉換為dict用於後續處理,將dict寫入excel

#

coding = 'utf-8'

import

time

import

xlrd,xlsxwriter

start =time.clock()

defread_excel(file):

"""讀入excel檔案

:rtype : object

:param file:

:return: 資料物件

"""try

: data =xlrd.open_workbook(file)

return

data

except

exception as err:

print

(err)

defwrite_excel(file):

"""讀入excel檔案

:rtype : object

:param file:

:return: 資料物件

"""try

: data =xlsxwrite.workbook(file)

return

data

except

exception as err:

print

(err)

defexcel_to_dict(read_excel_file,excel_title):

""":rtype : object

:return dict

"""dict2 ={}

data =read_excel(read_excel_file)

table = data.sheet_by_name(u'

bas_info')

for i in range(1,table.nrows):

row_content =table.row_values(i, 0, table.ncols)

dict1 =dict(zip(excel_title, row_content))

dict2[i] =dict1

return

dict2

defdict_to_excel(dict_content,excel_title):

"""將字典寫入excel中

:type dict_content: object dict

excel_title 列標題

"""dict_ing =dict_content

excel_init_file =xlsxwriter.workbook(out_excel_file)

table = excel_init_file.add_worksheet('

bas_info')

title_bold = excel_init_file.add_format()

border = excel_init_file.add_format()

for i,j in

enumerate(excel_title):

table.set_column(i,i,len(j)+1)

table.write_string(0,i,j,title_bold)

for k,v in

dict_content.items():

for i in

range(len(v)):

j =v.get(excel_title[i])

table.write_string(k,i,j,border)

table.set_column(1,1,16)

table.set_column(0,0,16)

excel_init_file.close()

if

__name__ == '

__main__':

read_excel_file = r'

d:\baspools_read.xlsx

'out_excel_file = r'

d:\baspools_out.xlsx

'excel_title = ['

basname

', '

basip

', '

location

', '

baslocation

', '

port

', '

basprovider

', '

portal_version

', '

timeout

', '

retry

','auth_type']

dict_content =excel_to_dict(read_excel_file,excel_title) #excel to dict

dict_to_excel(dict_content,excel_title) #dict to excel write to out_excel_file

end =time.clock()

print("

read: %f s

" % (end - start))

python excel讀寫資料

python 讀取excel內容,包含 日期處理 coding utf 8 import xlrd 讀取excel workbook xlrd.open workbook r d demo.xlsx 開啟excel檔案 table workbook.sheet by name sheet2 將檔案內...

python excel與csv文件之間的相互轉換

這裡主要用到了pandas庫,沒有該庫的話開啟cmd輸入pip install pandas就可以了 excel 轉 csv 使用pandas庫的read excel 函式和to csv 函式輕鬆搞定,例子如下 import pandas as pd import csv import xlrd 這...

Unity3D 讀寫XML檔案

在程式有時候需要從文字中讀取資料,或者把資料儲存到檔案中,使用xml檔案來儲存資料是乙個不錯的選擇。下面介紹一下在unity3d中使用c 如何進行xml檔案的讀寫。1 需要引入的包 using unityengine using system.collections using system.xml...