程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

讀excel和寫excel的方法(python)

編輯:Python
  • 讀寫excel的包很多,我這裡使用的時xlrd3 和 xlsxwriter 這兩個包
  • 代碼封裝如下
    讀excel
import xlrd3
import xlsxwriter
def read_excel_data(filename, data_type=None):
""" :param filename: 文件名 :param data_type: 返回數據類型,默認是list,如果data_type是True返回的是dict的類型的數據 :return: """
wb = xlrd3.open_workbook(filename)
sheet_01 = wb.sheet_by_index(0) # 選第一個sheet
res_list = []
if data_type:
start_index = 0
title = [ele.value for ele in sheet_01.row(start_index)]
for index in range(1, sheet_01.nrows): # 從第一行開始讀取,標題不讀
row_list = sheet_01.row(index)
if data_type:
row_data = {
title[k_index]: ele.value for k_index, ele in enumerate(row_list)}
else:
row_data = [ele.value for ele in row_list]
res_list.append(row_data)
return res_list

寫excle_
代碼如下

def write_to_excel_data(data_list, file_name, title=None, sheet_name="sheet1"):
""" :param data_list: 寫入數據[{}] 或者 [[]] :param title: 標題 :param file_name: 文件名 :param sheet_name: 工作薄 :return: """
workfile = xlsxwriter.Workbook(file_name)
worksheet = workfile.add_worksheet(sheet_name)
if not isinstance(title, (tuple, list)):
return "標題數據格式不對"
row_index, col_index = 0, 0
start_index = 0
# 設置背景色
if not sheet_name:
format = workfile.add_format()
format.set_bg_color("green")
if title:
worksheet.write_row(row_index, col_index, title)
start_index = 1
# dict 數據寫入
if isinstance(data_list[0], dict):
for index, item in enumerate(data_list, start_index):
ele = [item.get(key) for key in title]
worksheet.write_row(index, col_index, ele)
pass
# list 數據寫入
else:
for index, item in enumerate(data_list, start_index):
worksheet.write_row(index, col_index, item)
workfile.close()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved