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

1.Python 讀 excel數據

  • 使用Python 讀 excel數據,首先需要使用xlrd.open_workbook(文件名)來打開Excel文件,默認是rb方式打開;
  • 然後可以通過xlrd庫對象中的方法來獲取Excel文件信息,讀取excel數據;

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(員工基本信息)

# 顯示錶格的行數,和列數
print(sheet.nrows)
print(sheet.ncols)

# 讀取第二行的所有cell中的內容
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表中時間轉換為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)方法可以獲取指定行數或者列數的信息,其中i是從0開始計數的,這兩個方法都是返回list對象
  • cell_value(i, j)方法可以讀取單元格數據,i是行數,j是列數,行數和列數都是從0開始計數
  • 在excel中0表示empty,1表示string,2表示number,3表示date,4表示boolean,5表示error

2.將Excel數據轉換為json寫入到文件

  • 首先需要打開excel文件,然後通過名字拿到對應sheet,然後就可以開始操作excel表格;
  • 先創建一個空列表,獲取excel表格中的第一行作為字典的key值;然後在局部變數中創建一個字典對象(每次新的循環,字典對象需求清空),通過兩層循環(外循環控制行,內循環控制列)進行取值,將取到的值賦值給字典對象,每次循環完畢都將字典對象添加到定義的空列表中;

    要將數據寫入文件中,可以使用with上下文管理器,通過json.dumps()方法將之前存放數據的自定義列表進行序列化,然後寫入文件,想輸出真正的中文需要指定參數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

# 創建一個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)

參考:

歡迎登島修鍊武功_俠課島?

www.9xkd.com圖標
推薦閱讀:

相關文章