我有 4 个 .csv 文件,每天都会对其进行整理。我将解析的 csv 文件的输出保存为 4 个单独的 .xlsx 工作簿。我的目标是将所有 4 个工作簿合并为一个 xlsx 工作簿,每个工作簿包含在自己的选项卡/工作表中。
我读过很多使用 openpyxl、xlwt 和 xlwriter 以及其他人的版本来执行此操作的方法,但我只是感到困惑,并寻求专家的指导以了解正确的方法,以使这项工作适合我的特定应用程序。 .
我创建了包含 4 个工作表/选项卡的工作簿,但是当我尝试使用工作表名称写入选项卡时,它似乎会覆盖我之前所做的所有内容,而我只是不知道如何修复它?非常感谢任何帮助或指导!
import pandas as pd
import openpyxl
import csv
from openpyxl import Workbook
# this creates an xlsx workbook with 4 worksheets
wb = Workbook()
dest_filename = 'Drop Offenderssssssss.xlsx'
ws = wb.active
ws.title = "DropCount_Offenders"
ws = wb.create_sheet()
ws.title = 'Dropstat_Offenders'
ws = wb.create_sheet()
ws.title = 'DropCountPerSec_Offenders'
ws = wb.create_sheet()
ws.title = 'numPktDrops_Offenders'
wb.save(filename = dest_filename)
# there are 2 possible filenames. this takes user input and stores it as a global date variable to call proper filename
date = str(raw_input("Enter yyyymmdd: "))
date_var = date
# function 1 for tab1 contents:
def dropcount_offenders():
global date_var
filename1 = 'PROBE_HEALTH_GRAPH_Drop_Count_%s-01.01.00.AM.csv' %(date_var)
filename2 = 'PROBE_HEALTH_GRAPH_Drop_Count_%s-01.01.01.AM.csv' %(date_var)
# this trys to open the first possible filename
try:
file_handler = open(filename1)
except:
print"trying the next one"
# if first filename was not found then it locates and opens the 2nd possible filename
try:
file_handler = open(filename2)
except:
print"invalid input"
# this uses pandas library to read the csv contents into memory
data = pd.read_csv(file_handler)
# this renames the columns (takes out spaces)
data.columns = ["Probe_Name", "Recording_Time", "Drop_Count"]
# this defines a filter threshold which clears all rows who's Drop_Count column data = 0
counts = data[data.Drop_Count >= 1].sort_index(by="Probe_Name", ascending=True)
# now I want to append/write my filtered data to a specific tab within the xlsx file
counts.to_excel("Drop Offenderssssssss.xlsx", "DropCount_Offenders")
# function 2 for tab2 contents (overwrites all tabs I previously created and overwrites function 1 as well?):
def dropstat_offenders():
global date_var
filename1 = 'DropStats_%s-01.01.00.AM.csv' %(date_var)
filename2 = 'DropStats_%s-01.01.01.AM.csv' %(date_var)
try:
file_handler = open(filename1)
except:
print"trying the next one"
try:
file_handler = open(filename2)
except:
print"invalid input"
data = pd.read_csv(file_handler)
data.columns = ["Probe_Name", "RecordingTime", "RecordingPeriod", "PrimaryDimension", "BladeId", "dropCount"]
# this removes the columns i dont need to see
del data["RecordingPeriod"]
del data["BladeId"]
drops = data[data.dropCount >= 1].sort_index(by="Probe_Name", ascending=True)
drops.to_excel("Drop Offenderssssssss.xlsx", 'Dropstat_Offenders')
# this runs the above 2 functions in sequence
dropcount_offenders()
dropstat_offenders()
我想要的是 dropcount_offenders() 成为工作簿中的一个选项卡/工作表,而 dropstat_offenders() 成为另一个选项卡/工作表,等等...?
我认为可能有用但没有成功的一个snipit: Modify an existing Excel file using Openpyxl in Python
另一个snipit我不明白如何在我的应用程序中使用: How to concatenate three excels files xlsx using python?
最佳答案
我没有使用 Pandas 的经验,但你可能在这里不需要它。目前尚不清楚您是否要修改现有的 Excel 文件,或者是否只需要使用 csv 文件创建一个文件。如果是前者,您只能使用 openpyxl,如果是后者,您可以使用 openpyxl 或 xlsxwriter。 python-excel(xlrd 和 xlwt)不支持编辑现有或写入 Excel 2010 文件。
假设您想要将 csv 文件转换为 Excel 工作表,您的代码将类似于以下伪代码。
from csv import DictReader
from openpyxl import Workbook
wb = Workbook()
del wb["Sheet"]
for title in ("DropCount_Offenders", "Dropstat_Offenders", "DropCountPerSec_Offenders", "numPktDrops_Offenders"):
wb.create_sheet(title)
for f in filenames:
src = DictReader(f)
ws = wb[f]
ws.append(["Probe_Name", "Recording_Time", "Drop_Count"])
for row in src:
ws.append(row["Probe_Name"], ["Recording_Time"], ["Drop_Count"])
wb.save("Drop Offenders.xlsx")
您需要查看标准库中的 csv 模块以获取更多信息。
如果您确实需要 Pandas 进行排序等,那么您需要查看用于编辑现有 Excel 文件的文档。
注意。无需在函数中使用global
。在 Python 中,始终可以读取更高范围内的变量。 global
用于使局部变量成为全局变量,您几乎永远不需要它。
关于python - 使用 Python 将多个工作簿合并为一个 xlsx 工作簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28405182/