import numpy as np import pandas as pd import openpyxl from openpyxl.styles import numbers df_csv = pd.read_csv(r'Permance_a.csv', index_col=0, encoding='utf-8') df_csv.to_excel(r'Permance_a.xlsx') # 源表格和目标表格的文件名 source_file = u'Permance_a.xlsx' target_file = u'Permance2.xlsx' # 要复制的单元格位置 source_start_row = 2 # 开始行 source_start_col = 5 # 开始列 source_end_row = 11 # 结束行 source_end_col = 8 # 结束列 # 要覆盖的单元格位置 target_start_row = 7 # 开始行 target_start_col = 3 # 开始列 target_end_row = 16 # 结束行 target_end_col = 6 # 结束列 # 打开两个工作簿 wb1 = openpyxl.load_workbook(source_file) ws1 = wb1.active wb2 = openpyxl.load_workbook(target_file) ws2 = wb2.active # 将源表格的数据覆盖到目标表格中 for i in range(source_start_row, source_end_row + 1): for j in range(source_start_col, source_end_col + 1): cell1 = ws1.cell(row=i, column=j) cell2 = ws2.cell(row=i + target_start_row - source_start_row, column=j + target_start_col - source_start_col) cell2.value = cell1.value # 保存目标表格 wb2.save(target_file) 生成目标文件的单元格显示:此单元格中的数字为文本格式,或者其前面有撇号,修改以上代码解决该问题
时间: 2023-07-16 17:16:43 浏览: 172
可以在将数据覆盖到目标表格之前,先将目标表格中相关单元格的格式设置为数字格式,可以使用openpyxl.styles中的numbers模块来实现。
修改后的代码如下:
```
import numpy as np
import pandas as pd
import openpyxl
from openpyxl.styles import numbers
df_csv = pd.read_csv(r'Permance_a.csv', index_col=0, encoding='utf-8')
df_csv.to_excel(r'Permance_a.xlsx')
# 源表格和目标表格的文件名
source_file = u'Permance_a.xlsx'
target_file = u'Permance2.xlsx'
# 要复制的单元格位置
source_start_row = 2 # 开始行
source_start_col = 5 # 开始列
source_end_row = 11 # 结束行
source_end_col = 8 # 结束列
# 要覆盖的单元格位置
target_start_row = 7 # 开始行
target_start_col = 3 # 开始列
target_end_row = 16 # 结束行
target_end_col = 6 # 结束列
# 打开两个工作簿
wb1 = openpyxl.load_workbook(source_file)
ws1 = wb1.active
wb2 = openpyxl.load_workbook(target_file)
ws2 = wb2.active
# 将目标表格中相关单元格的格式设置为数字格式
for i in range(target_start_row, target_end_row + 1):
for j in range(target_start_col, target_end_col + 1):
cell = ws2.cell(row=i, column=j)
cell.number_format = numbers.FORMAT_NUMBER
# 将源表格的数据覆盖到目标表格中
for i in range(source_start_row, source_end_row + 1):
for j in range(source_start_col, source_end_col + 1):
cell1 = ws1.cell(row=i, column=j)
cell2 = ws2.cell(row=i + target_start_row - source_start_row, column=j + target_start_col - source_start_col)
cell2.value = cell1.value
# 保存目标表格
wb2.save(target_file)
```
这样就可以保证生成的目标文件中的单元格都是数字格式了。
阅读全文