import openpyxl
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
import os
def copy_all_sheets_xlsx(input_file, output_file):
try:
wb_source = load_workbook(filename=input_file)
except FileNotFoundError:
print(f"无法找到源文件: {input_file}")
return
except Exception as e:
print(f"无法打开源文件 {input_file}: {e}")
return
wb_new = openpyxl.Workbook()
default_sheet = wb_new.active
wb_new.remove(default_sheet)
for sheet_name in wb_source.sheetnames:
source_sheet = wb_source[sheet_name]
target_sheet = wb_new.create_sheet(title=sheet_name)
print(f"正在复制工作表: {sheet_name}")
for row in source_sheet.iter_rows():
for cell in row:
new_cell = target_sheet.cell(row=cell.row, column=cell.column, value=cell.value)
if cell.has_style:
new_cell.font = cell.font
new_cell.border = cell.border
new_cell.fill = cell.fill
new_cell.number_format = cell.number_format
new_cell.protection = cell.protection
new_cell.alignment = cell.alignment
for column_cells in source_sheet.columns:
length = max(len(str(cell.value)) if cell.value is not None else 0 for cell in column_cells)
column_letter = get_column_letter(column_cells[0].column)
target_sheet.column_dimensions[column_letter].width = length + 2
try:
wb_new.save(output_file)
print(f"所有工作表已成功复制到 '{output_file}'")
except Exception as e:
print(f"无法保存目标文件 {output_file}: {e}")
if __name__ == "__main__":
input_xlsx = r'E:\Pro\书\pptx\月饼\超级工具定制\界址点成果表.xlsx'
output_xlsx = r'E:\Pro\书\pptx\月饼\超级工具定制\复制后的文件.xlsx'
if not os.path.isfile(input_xlsx):
print(f"源文件不存在: {input_xlsx}")
else:
copy_all_sheets_xlsx(input_xlsx, output_xlsx)