导入多个.xlsx文件并使用 openpyxl 将数据操作数据写入具有多个工作表的单个新 xlsx 文件中执行算术运算?



>''' 我正在使用openpyxl打开一个xlsx文件并进行一些算术运算,然后将其保存在新的xlsx文件中。现在我想导入许多文件并希望操作相同的内容并将所有文件结果存储在单个 xlsx 文件多张表中。
'''

from openpyxl import Workbook
import openpyxl
wb= openpyxl.load_workbook(filename=r"C:UsersserverDesktopPythonData.xlsx", read_only=True)
# resading file from
ws = wb['Sheet1'] # moving into sheet1
# Comprehension
row_data = [  [cell.value for cell in row] for row in ws.rows] # looping through row data in sheet
header_data = row_data[0] # leaving header data by slicing
row_data = row_data[1:] #storing xlsx file data into 2D list
[ dp.append(dp[1]*dp[2])for dp in row_data] # perfornming multplication opertion columnwise, lets say coulmn 1 * column 2 in a row_data and appending into next column
wb.close()# closing the worksheet
wb = openpyxl.Workbook() # opening new worksheet 
ws = wb.active # sheet 1 is active`enter code here`
ws.append(header_data) # header data writtten
for row in row_data: # 2D list data is writng in sheet 1
ws.append(row)
wb.save(r"C:UsersserverDesktopPythonResult.xlsx")

'''我可以在一个列表中存储多个xlsx文件,现在我想访问每个文件数据并执行一些算术运算,最后结果数据需要存储在包含多个工作表的单个xlsx文件中 '''

from openpyxl import Workbook
import openpyxl
import os 
location=r"C:UsersserverDesktopPythonData.xlsx" # will get folder location here where many xlsx files are present
counter = 0 #keep a count of all files found
xlsx_files = [] #list to store all xlsx files found at location
for file in os.listdir(wb):
try:
if file.endswith(".xlsx"):
print ("xlsx file found:t", file)
xlsx_files.append(str(file))
counter = counter+1

except Exception as e:
raise e
print ("No files found here!")
print ("Total files found:t", counter)

最新更新