1.需求描述
現在有三個工作表,如下:
並且每個工作表中的內容如下:
需要將這三個工作簿中的分數這一列合並到一起,最終實現效果如下圖:
2.實現代碼
# Author:Logan
# Date:2020/6/2 9:58
# IDE:PyCharm
# version:Python 3.5
import xlrd
import xlwt
from xlutils.copy import copy
import os
def create_excel(path, sheet_name):
workbook = xlwt.Workbook() # 新建一個工作簿
workbook.add_sheet(sheet_name) # 在工作簿中新建一個表格
workbook.save(path) # 保存工作簿
def read_data(FileName):
# 1.打開文件
open_file = xlrd.open_workbook(FileName)
# 2.讀取第二列的內容(表中第一列索引值為0)
st = open_file.sheet_by_index(0)
data = [st.cell_value(i,1) for i in range(1, st.nrows)]
# 3.將表名追加到列表作為第一個元素
title = open_file.sheet_names()
data = title + data
return data
def write_data(path, data):
index = len(data) # 獲取索引寫入的行數
workbook = xlrd.open_workbook(path) # 打開工作簿
sheets = workbook.sheet_names() # 獲取工作簿中的所有表格
worksheet = workbook.sheet_by_name(sheets[0]) # 獲取工作簿中所有表格中的的第一個表格
cols_old = worksheet.ncols # 獲取表格中已存在的數據的列數
new_workbook = copy(workbook) # 將xlrd對象拷貝轉化為xlwt對象
new_worksheet = new_workbook.get_sheet(0) # 獲取轉化后工作簿中的第一個表格
for i in range(0, index):
new_worksheet.write( i, cols_old + 1, data[i]) # 追加寫入數據
new_workbook.save(path) # 保存工作簿
def get_file_name(file_dir):
tmp_lst = []
for root, dirs, files in os.walk(file_dir):
for file in files:
tmp_lst.append(os.path.join(root, file))
return tmp_lst
def main():
DIR_NAME = r'D:\test\\'
create_excel(DIR_NAME + '合並.xls','匯總數據')
print(DIR_NAME + '合並.xls')
tmp_list = get_file_name(DIR_NAME + 'data\\')
for dir in tmp_list:
data = read_data(dir)
write_data(DIR_NAME + '\合並.xls', data)
print('------------'+ dir.split("\\")[-1] + '數據寫入成功!-----------' )
if __name__ == '__main__':
main()
程序運行截圖: