使用 openpyxl
思路:
- 讀取n個excel的文件,存儲在一個二維數(shù)組中,注意需要轉(zhuǎn)置。
- 將二維數(shù)組的數(shù)據(jù)寫入excel。
安裝軟件:文章來源:http://www.zghlxwxcb.cn/news/detail-631102.html
pip install openpyxl
源代碼:
import os
import openpyxl
# 將n個excel文件數(shù)據(jù)合并到一個excel
# 讀取n個excel文件數(shù)據(jù),并且合并到一個二維數(shù)組,每個excel只讀取A列,且行數(shù)保持一樣
def merge(n):
data = []
for i in range(n):
data_file_path = os.path.join('data', f'data{i + 1}.xlsx')
# 返回一個workbook數(shù)據(jù)類型的值
workbook = openpyxl.load_workbook(data_file_path)
sheet = workbook.active
# 取A列數(shù)據(jù)
cell = sheet['A']
column = []
for j in cell:
column.append(j.value)
data.append(column)
# print(data)
# 轉(zhuǎn)置
transpose_data = list(map(list, zip(*data)))
# print(transpose_data)
merge_file_path = os.path.join('data', 'merge.xlsx')
save(transpose_data, merge_file_path)
# 將二維數(shù)據(jù)數(shù)據(jù)保存到excel文件
def save(data, file_path):
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.title = 'Sheet1'
workbook.save(file_path)
for row in data:
sheet.append(row)
workbook.save(file_path)
if __name__ == '__main__':
merge(10)
效果截圖:
使用 pandas
思路:
- 讀取n個excel的文件,存儲在一個二維數(shù)組中,注意需要轉(zhuǎn)置。
- 將二維數(shù)組的數(shù)據(jù)寫入excel。
安裝軟件:
pip install pandas
源代碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-631102.html
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import pandas as pd
import os
# 將n個excel文件數(shù)據(jù)合并到一個excel
# 讀取n個excel文件數(shù)據(jù),并且合并到一個二維數(shù)組,每個excel只讀取A列,且行數(shù)保持一樣
def merge(n):
data = []
for i in range(n):
data_file_path = os.path.join('data', f'data{i + 1}.xlsx')
df = pd.read_excel(data_file_path, index_col=None, header=None, sheet_name='Sheet1')
# 僅獲取第0列數(shù)據(jù)
data.append(df.values[:, 0])
# print(data)
# 轉(zhuǎn)置
transpose_data = list(map(list, zip(*data)))
# print(transpose_data)
merge_file_path = os.path.join('data', 'merge.xlsx')
save(transpose_data, merge_file_path)
# 將二維數(shù)據(jù)數(shù)據(jù)保存到excel文件
def save(data, file_path):
df = pd.DataFrame(data)
# 寫入本地excel文件
df.to_excel(file_path, sheet_name="Sheet1", index=False, header=False)
# main函數(shù)
if __name__ == '__main__':
merge(10)
參考
- https://zhuanlan.zhihu.com/p/353669230
- https://blog.csdn.net/weixin_44288604/article/details/120731317
- https://zhuanlan.zhihu.com/p/363810440
- https://baijiahao.baidu.com/s?id=1737230506657192730&wfr=spider&for=pc
- 二維數(shù)組轉(zhuǎn)置
源代碼位置:
- 源代碼-openpyxl
- 源代碼-pandas
- github地址
到了這里,關(guān)于python 合并多個excel文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!