简而言之,我希望能够:
- 选择一个文件是csv,或任何excel
- 从那份文件
- 对所需的选择应用筛选器
- 将应用过滤视图保存到一个新文件xls中,该文件xls只是在当前文件夹的文件名中添加了“forreview
'
# Import the necessary libraries
import openpyxl
import os
import time
import csv
# Define the path to the CSV file
csv_file = "C:/Users/USERNAME//Desktop/filename.csv"
# Open the CSV file and create a reader object
with open(csv_file, "r") as f:
reader = csv.reader(f)
# Iterate over the rows in the reader
rows = []
for row in reader:
rows.append(row)
# Open the Excel document and create a new worksheet
wb = openpyxl.Workbook()
ws = wb.active
# Write the rows from the CSV file to the Excel worksheet
for row in rows:
ws.append(row)
# Apply filters to the top row
ws.auto_filter.ref = "A1:Z1"
# Filter column A by "Network Upload Egress" and "Removable Media Egress"
ws.auto_filter.add_filter_column(0, \["Network Upload Egress", "Removable Media Egress"\])
# Save a copy of the Excel document with "Evidence Review" added to the file name
new_file = os.path.splitext(excel_file)\[0\] + " Evidence Review.xlsx"
# Display a loading animation while the process is running
print("Processing...")
for i in range(10):
time.sleep(0.5)
print(".", end="")
# Save the copy of the Excel document
try:
wb.save(new_file)
print("\\nProcess complete!")
except IOError:
print("Error saving the copy of the Excel document. Make sure you have permission to save files to the specified location.")`
1条答案
按热度按时间xe55xuns1#
请尝试下面的代码。
导入csv
定义过滤器csv(输入文件、输出文件、过滤器列、过滤器值):将open(输入文件,"r")作为输入文件,将open(输出文件,"w",换行符="")作为输出文件:#创建CSV读取器和写入器读取器= csv.读取器(输入文件)写入器= csv.写入器(输出文件)
用法示例
filter_csv("输入. csv","输出. csv","状态","CA")