继续完善以上代码
时间: 2023-07-02 16:18:58 浏览: 47
好的,以下是一个稍微完善一些的 Python 程序,除了抽取特定的数据并将其写入另一个 Excel 文件中,它还会检查输入的 Excel 文件和输出的 Excel 文件是否存在以及是否具有正确的工作表和列。如果有任何错误,程序将输出错误消息并停止运行。
```python
import openpyxl
import os
# 输入文件名和工作表名
input_file = 'example.xlsx'
input_sheet = 'Sheet1'
# 输出文件名和工作表名
output_file = 'output.xlsx'
output_sheet = 'Result'
# 输入文件和输出文件的路径
input_path = os.path.abspath(input_file)
output_path = os.path.abspath(output_file)
# 检查输入文件是否存在
if not os.path.exists(input_path):
print(f'Error: Input file "{input_file}" not found.')
exit()
# 检查输出文件是否存在
if os.path.exists(output_path):
print(f'Warning: Output file "{output_file}" already exists and will be overwritten.')
os.remove(output_path) if os.path.exists(output_path) else None
# 打开输入的 Excel 文件
wb_in = openpyxl.load_workbook(input_path)
# 检查输入的 Excel 文件是否具有指定的工作表
if input_sheet not in wb_in.sheetnames:
print(f'Error: Input file "{input_file}" does not have sheet "{input_sheet}".')
exit()
# 选择名为 input_sheet 的工作表
sheet_in = wb_in[input_sheet]
# 新建输出的 Excel 文件
wb_out = openpyxl.Workbook()
# 选择名为 output_sheet 的工作表
sheet_out = wb_out[output_sheet]
# 检查第一列和第三列是否存在
if not all([col[0].value.lower() == 'column 1' for col in sheet_in.iter_cols(min_row=1, max_row=1, min_col=1, max_col=1)]):
print(f'Error: Input file "{input_file}" does not have column 1.')
exit()
if not all([col[0].value.lower() == 'column 3' for col in sheet_in.iter_cols(min_row=1, max_row=1, min_col=3, max_col=3)]):
print(f'Error: Input file "{input_file}" does not have column 3.')
exit()
# 从输入的 Excel 文件中抽取数据并写入输出的 Excel 文件中
for row_in in sheet_in.iter_rows(min_row=2):
row_out = [row_in[0].value, row_in[2].value]
sheet_out.append(row_out)
# 保存输出的 Excel 文件
wb_out.save(output_path)
print(f'Success: Data has been extracted from "{input_file}" and written to "{output_file}".')
```
请注意,在运行此程序之前,您需要先安装 OpenPyXL 库(通过运行“pip install openpyxl”命令)。此外,您需要将“example.xlsx”文件和此 Python 文件保存在同一目录中。