首页 > 解决方案 > 多选项卡 Excel 工作表,1 列中的唯一条目,以另一列中的数据为名称创建新文件,全部带有标题

问题描述

像往常一样,我咬得比我能咀嚼的还多。我有一个文件“list.xlsx”。该文件有 3 张纸,“当前学生”、“已完成”和“已取消”。这些工作表都包含以下标题下的数据 [StudentId, FirstName, Lastname, DoB, Nationality, CourseID, CourseName, Startdate, Finishdate, UnitID, UnitName, UnitCompetency]

我创建了以下可憎的东西,它从我需要的东西开始。

我想要它做的是:

1)在以其工作表命名的文件夹中基于 StudentId(唯一)创建一个包含 FirstName + Lastname.xlsx 的文件

2)在该文件中,从其余列中获取所有信息并将其附加到其文件中

    #python 3.8
import pandas as pd
import os
import shutil

file = "list.xlsx"
CS = "current student"
Fin = "finished"
Can = "cancelled"
TheList = {CS, Fin, Can}
CanXlsx = pd.read_excel(file, sheet_name = Can)
FinXlsx = pd.read_excel(file, sheet_name = Fin)
CSXlsx = pd.read_excel(file, sheet_name = CS)

if os.path.exists(CS):
    shutil.rmtree(CS)
os.mkdir(CS)
CSDir = '//current student//'
if os.path.exists(Fin):
    shutil.rmtree(Fin)
os.mkdir(Fin)
FinDir = '//finished//'
if os.path.exists(Can):
    shutil.rmtree(Can)
os.mkdir(Can)
CanDir = '//cancelled//'

CancelID = CanXlsx.StudentId.unique()
FinID = FinXlsx.StudentId.unique()
CSID = CSXlsx.StudentId.unique()

我以为我在使用 for 循环等方面做得更好,但似乎无法理解它们。我可以考虑逻辑,但它只是没有通过代码来实现。

https://drive.google.com/file/d/134fqWx6veF7zp_12GqFYlbmPZnK8ihaV/view?usp=sharing

标签: pythonexcelpandasxlsxxlsxwriter

解决方案


我认为为此所需的方法是创建 3 个数据框(可能可以用一个来完成,但我不记得了)。1)然后,在每个数据框上,您需要提取“名字+姓氏”列表,然后,2)您需要在数据框上创建掩码以提取信息并保存。

import os
import shutil

file = "list.xlsx"
CS = "current student"
Fin = "finished"
Can = "cancelled"
TheList = {CS, Fin, Can}
CanXlsx = pd.read_excel(file, sheet_name = Can)
FinXlsx = pd.read_excel(file, sheet_name = Fin)
CSXlsx = pd.read_excel(file, sheet_name = CS)

## File Creation
if os.path.exists(CS):
    shutil.rmtree(CS)
os.mkdir(CS)
CSDir = '//current student//'
if os.path.exists(Fin):
    shutil.rmtree(Fin)
os.mkdir(Fin)
FinDir = '//finished//'
if os.path.exists(Can):
    shutil.rmtree(Can)
os.mkdir(Can)
CanDir = '//cancelled//'

# Create full names
CanXlsx["Fullname"] = CanXlsx["StudentId"] + "_" + CanXlsx["First Name"] + "_" + CanXlsx["Last Name"]
## Same for the other dfs

# Get a list of ids
# canFullNames = list(CanXlsx["Fullname"]) Edit: Preferred approach through student Ids
canIds = list(CanXlsx["StudentId"])
## Same for the other dfs

# Loop over the list of full names to create your df
for id in canIds:
    df1 = CanXlsx[CanXlsx["StudenId"] == id] # This will filter the rows by the id you want
    # Retrieve the full name
    name = df1.iloc[0]["Fullname"]

    # Create the filename
    filename = os.path.join(CanDir,name + ".xlsx")

    df1.drop(columns = ["First Name", "Last Name"] # I understand that these columns are not required on each file
    df1.to_excel(filename,header=True,index=False)

## Same for the other dfs

让我知道这是否有帮助,至少这是我理解你想用你的代码实现的。:D


推荐阅读