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

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

from openpyxl import Workbook
import openpyxl
wb= openpyxl.load_workbook(filename=r"C:\Users\server\Desktop\Python\Data.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:\Users\server\Desktop\Python\Result.xlsx")


geiwoaidechibang 回答:导入多个.xlsx文件并使用openpyxl将数据操作的数据写到具有多个工作表的单个新xlsx文件中,然后对数据进行数据运算来执行算术运算?

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

from openpyxl import Workbook
import openpyxl
import os 

location=r"C:\Users\server\Desktop\Python\Data.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)
本文链接:https://www.f2er.com/3034016.html

大家都在问