如何将Excel中带特定格式的Chart工作表复制到新文件
保留格式复制Excel工作表至新文件
需求:将包含名为「Chart」且带有特定格式(如颜色、边框等)的Excel工作表,完整复制到新Excel文件中,确保所有格式完全保留。
以下是基于openpyxl实现的代码:
import openpyxl def copy_worksheet(source_ws, target_ws): for row in source_ws.iter_rows(): for cell in row: # 复制单元格值 target_ws[cell.coordinate].value = cell.value # 复制格式相关属性 target_ws[cell.coordinate].font = cell.font.copy() target_ws[cell.coordinate].border = cell.border.copy() target_ws[cell.coordinate].fill = cell.fill.copy() target_ws[cell.coordinate].number_format = cell.number_format target_ws[cell.coordinate].protection = cell.protection.copy() target_ws[cell.coordinate].alignment = cell.alignment.copy() # 复制单元格批注 target_ws[cell.coordinate].comment = cell.comment def main(): # 配置文件路径和工作表名称 source_file = "C:/Users/user1/testsheet.xlsx" source_sheet_name = "Chart" output_file = "C:/Users/user1/output.xlsx" # 加载源工作簿并指定目标工作表 source_wb = openpyxl.load_workbook(source_file) source_ws = source_wb[source_sheet_name] # 创建新工作簿并设置工作表名称 output_wb = openpyxl.Workbook() output_ws = output_wb.active output_ws.title = source_sheet_name # 执行复制操作并保存文件 copy_worksheet(source_ws, output_ws) output_wb.save(output_file) if __name__ == "__main__": main()
关键说明
copy_worksheet函数遍历源工作表的每一个单元格,逐个复制值和所有格式属性:字体、边框、填充样式、数字格式、单元格保护、对齐方式,同时保留单元格批注。- 必须使用
.copy()方法复制格式对象,避免源对象和目标对象引用同一实例导致的异常。 - 主函数中需根据实际场景修改
source_file、source_sheet_name和output_file的路径与名称。
内容的提问来源于stack exchange,提问作者pleasehelpme
相关产品推荐
相关产品推荐

