使用Python将多个工作簿合并到一个xlsx工作簿中

时间:2015-02-09 07:59:34

标签: python excel csv xlwt openpyxl

我有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()是另一个选项卡/工作表等...?

我认为可能有效,但没有成功的一个片断: Modify an existing Excel file using Openpyxl in Python

另一个片段我不明白如何在我的应用程序中使用: How to concatenate three excels files xlsx using python?

2 个答案:

答案 0 :(得分:1)

我没有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文件。

NB。您无需在函数中使用global。在Python中,对更高范围内的变量的读访问始终可用。 global用于使局部变量成为全局变量,这是您几乎不需要的东西。

答案 1 :(得分:0)

将XlsxWriter与Pandas一起使用

使用Python将单个xlsx工作簿中的多个工作簿

import pandas as pd
import xlsxwriter

names = ['Sankar','Guru','Karthik','parthi','sarvanan']
grade = [88,84,89,84,81]
bscdegree = [1,1,0,0,1]
mscdegree = [2,1,0,0,0]
phddegree = [0,1,0,0,0]
bdaydates = ['04/15/1945','10/25/1976','3/30/1990','04/30/1901','1963-09-01']
department = ['CS','IT','CS&IT','ECE']
list = zip(names,bscdegree,mscdegree,phddegree,bdaydates)
list1 = zip(names,grade,department)
columns = ['Names','BSC','MSC','PHD','Bday']
columns1 = ['Names','Grades','Department']
df = pd.DataFrame(data=list, columns=columns)
df1 = pd.DataFrame(data=list1, columns=columns1)
writer = pd.ExcelWriter('grade.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1',index=False)
df1.to_excel(writer, sheet_name='sheet2',index=False)
writer.save()

http://xlsxwriter.readthedocs.io/working_with_pandas.html