如何用Openpyxl读取工作表内容并写入新工作表?
使用openpyxl读取并处理Excel数据后写入新文件
直接通过openpyxl操作Excel单元格的值,能避免中间存储导致的数据类型不兼容问题。以下是可实现读取源文件、处理数据后写入目标文件的代码,基于Michael Zippo的Python Engineering方案修改,加入了数据处理示例:
# 导入openpyxl模块 import openpyxl as xl # 打开源Excel文件 source_file = "C:\\Users\\Admin\\Desktop\\trading.xlsx" wb_source = xl.load_workbook(source_file) ws_source = wb_source.worksheets[0] # 打开目标Excel文件 target_file = "C:\\Users\\Admin\\Desktop\\test.xlsx" wb_target = xl.load_workbook(target_file) ws_target = wb_target.active # 获取源文件的总行数和总列数 max_row = ws_source.max_row max_col = ws_source.max_column # 遍历单元格,读取、处理后写入目标文件 for i in range(1, max_row + 1): for j in range(1, max_col + 1): # 读取源单元格的值 cell_value = ws_source.cell(row=i, column=j).value # 自定义数据处理逻辑示例:数值类型数据乘以2 if isinstance(cell_value, (int, float)): cell_value = cell_value * 2 # 将处理后的值写入目标单元格 ws_target.cell(row=i, column=j).value = cell_value # 保存目标文件 wb_target.save(target_file)
关键说明:
- 直接操作单元格的
.value属性,能保留Excel原生数据类型,避免中间列表转换时的类型丢失或不兼容问题 - 数据处理逻辑可根据需求自定义,只需插入在读取值和写入值的步骤之间
- 若目标文件不存在,可替换为
wb_target = xl.Workbook()创建新文件,再获取活动工作表进行写入
内容的提问来源于stack exchange,提问作者Milton C Dias Jr
相关产品推荐
相关产品推荐

