#!/bin/env python import numpy as np import pandas as pd import openpyxl,os df_csv = pd.read_csv(r'Permance_a.csv',index_col=0,encoding='utf-8') df_csv.to_excel(r'Permance_a.xlsx') # 打开Excel文件 wb = openpyxl.load_workbook('Permance_a.xlsx') # 选择第一个工作表 ws = wb.active # 循环遍历每一个单元格 for row in ws.iter_rows(): for cell in row: # 判断单元格是否包含% if '%' in str(cell.value): # 将单元格格式设置为数字格式 cell.number_format = '0.00%' # 将单元格值除以100并重新赋值给单元格 cell.value = float(cell.value.strip('%')) / 100 # 保存Excel文件 wb.save('Permance_a.xlsx') # 源表格和目标表格的文件名 source_file = r'Permance_a.xlsx' target_file = r'Permance.xlsx' source_end_col = 8 # 结束列 source_start_col = 5 # 开始列 source_start_row = [2,12,22,32] source_end_row = [11,21,31,41] target_end_col = 6 # 结束列 target_start_col = 3 # 开始列 target_start_row = [7,35,21,49] target_end_row = [16,44,30,58] # 打开两个工作簿 wb1 = openpyxl.load_workbook(source_file) ws1 = wb1.active target_ws_name = 'sd' + source_file[-6] wb2 = openpyxl.load_workbook(target_file) wb2.active.title = target_ws_name ws2 = wb2.active # 将源表格的数据覆盖到目标表格中 for i in range(len(source_start_row)): for row in range(source_start_row[i], source_end_row[i]+1): for col in range(source_start_col, source_end_col+1): value = ws1.cell(row=row, column=col).value ws2.cell(row=target_start_row[i]+row-source_start_row[i], column=target_start_col+col-source_start_col, value=value) # 保存目标表格 wb2.save(target_file) 修改以上代码,将目标文件中数据引用源中工作明修改为target_ws_name
时间: 2023-12-06 22:43:44 浏览: 140
python中import reload __import__的区别详解
修改后的代码如下:
```
#!/bin/env python
import numpy as np
import pandas as pd
import openpyxl,os
df_csv = pd.read_csv(r'Permance_a.csv',index_col=0,encoding='utf-8')
df_csv.to_excel(r'Permance_a.xlsx')
# 打开Excel文件
wb = openpyxl.load_workbook('Permance_a.xlsx')
# 选择第一个工作表
ws = wb.active
# 循环遍历每一个单元格
for row in ws.iter_rows():
for cell in row:
# 判断单元格是否包含%
if '%' in str(cell.value):
# 将单元格格式设置为数字格式
cell.number_format = '0.00%'
# 将单元格值除以100并重新赋值给单元格
cell.value = float(cell.value.strip('%')) / 100
# 保存Excel文件
wb.save('Permance_a.xlsx')
# 源表格和目标表格的文件名
source_file = r'Permance_a.xlsx'
target_file = r'Permance.xlsx'
source_end_col = 8 # 结束列
source_start_col = 5 # 开始列
source_start_row = [2,12,22,32]
source_end_row = [11,21,31,41]
target_end_col = 6 # 结束列
target_start_col = 3 # 开始列
target_start_row = [7,35,21,49]
target_end_row = [16,44,30,58]
# 打开两个工作簿
wb1 = openpyxl.load_workbook(source_file)
ws1 = wb1.active
# 修改目标工作表名
target_ws_name = 'sd' + source_file[-6]
wb2 = openpyxl.load_workbook(target_file)
wb2[target_ws_name].title = target_ws_name
ws2 = wb2[target_ws_name]
# 将源表格的数据覆盖到目标表格中
for i in range(len(source_start_row)):
for row in range(source_start_row[i], source_end_row[i]+1):
for col in range(source_start_col, source_end_col+1):
value = ws1.cell(row=row, column=col).value
ws2.cell(row=target_start_row[i]+row-source_start_row[i], column=target_start_col+col-source_start_col, value=value)
# 保存目标表格
wb2.save(target_file)
```
阅读全文