西红门网站建设公司,国家查企业信息查询平台,网站做跳转,在线制作横幅使用 openpyxl
思路#xff1a;
读取n个excel的文件#xff0c;存储在一个二维数组中#xff0c;注意需要转置。将二维数组的数据写入excel。
安装软件#xff1a;
pip install openpyxl源代码#xff1a;
import os
import openpyxl
# 将n个excel文件数据合并到一个…使用 openpyxl
思路
读取n个excel的文件存储在一个二维数组中注意需要转置。将二维数组的数据写入excel。
安装软件
pip install openpyxl源代码
import os
import openpyxl
# 将n个excel文件数据合并到一个excel# 读取n个excel文件数据并且合并到一个二维数组每个excel只读取A列且行数保持一样
def merge(n):data []for i in range(n):data_file_path os.path.join(data, fdata{i 1}.xlsx)# 返回一个workbook数据类型的值workbook openpyxl.load_workbook(data_file_path)sheet workbook.active# 取A列数据cell sheet[A]column []for j in cell:column.append(j.value)data.append(column)# print(data)# 转置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)# 将二维数据数据保存到excel文件
def save(data, file_path):workbook openpyxl.Workbook()sheet workbook.activesheet.title Sheet1workbook.save(file_path)for row in data:sheet.append(row)workbook.save(file_path)if __name__ __main__:merge(10)
效果截图 使用 pandas
思路
读取n个excel的文件存储在一个二维数组中注意需要转置。将二维数组的数据写入excel。
安装软件
pip install pandas源代码
#!/usr/bin/python3
# -*- coding: utf-8 -*-import pandas as pd
import os# 将n个excel文件数据合并到一个excel# 读取n个excel文件数据并且合并到一个二维数组每个excel只读取A列且行数保持一样
def merge(n):data []for i in range(n):data_file_path os.path.join(data, fdata{i 1}.xlsx)df pd.read_excel(data_file_path, index_colNone, headerNone, sheet_nameSheet1)# 仅获取第0列数据data.append(df.values[:, 0])# print(data)# 转置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)# 将二维数据数据保存到excel文件
def save(data, file_path):df pd.DataFrame(data)# 写入本地excel文件df.to_excel(file_path, sheet_nameSheet1, indexFalse, headerFalse)# main函数
if __name__ __main__:merge(10)
参考
https://zhuanlan.zhihu.com/p/353669230https://blog.csdn.net/weixin_44288604/article/details/120731317https://zhuanlan.zhihu.com/p/363810440https://baijiahao.baidu.com/s?id1737230506657192730wfrspiderforpc二维数组转置
源代码位置
源代码-openpyxl源代码-pandasgithub地址