如果报错请检查python版本是否正确,包是否成功引入
可以直接实现对单个表格的判断重复操作
import csv
from openpyxl import Workbook
from collections import defaultdict
def read_csv_file_and_write_to_excel(csv_file_path, excel_file_path):
# 创建一个新的工作簿和工作表对象
wb = Workbook()
ws = wb.active
# 打开CSV文件并读取内容
with open(csv_file_path, newline='') as csvfile:
csv_reader = csv.reader(csvfile)
row_idx = 1 # 行索引
col_idx = 1 # 列索引
previous_values = defaultdict(list) # 用于跟踪已写入的值
for row in csv_reader:
for value in row:
if value.strip():
if value.startswith('ZY'):
# 如果值以'ZY'开头,则换行写入
row_idx += 1
col_idx = 1
value = value.replace('ZY', 'ZY') # 移除'ZY'前缀
ws.cell(row=row_idx, column=col_idx, value=value)
# 判断是否有重复值
if value in previous_values[col_idx]:
# 获取重复值的索引列表
repeat_indices = [i + 1 for i, x in enumerate(previous_values[col_idx]) if x == value]
# 在最后一列写入重复的单元格信息
ws.cell(row=row_idx, column=col_idx + 1, value=value)
previous_values[col_idx].append(value)
col_idx += 1
# 保存工作簿到指定的Excel文件
wb.save(excel_file_path)
print(f"Data from '{csv_file_path}' has been written to '{excel_file_path}'.")
# 定义CSV文件路径和Excel文件路径
csv_file_path = '1.csv'
excel_file_path = 'hskst.xlsx'
# 调用函数读取CSV文件并写入到Excel文件
read_csv_file_and_write_to_excel(csv_file_path, excel_file_path)