问题:按单位拆分,一个单位一个文件,一个文件中有类别中“在编”“试用”“镇聘”三个工作表,分别存入相关的数据
【pytthon代码】
代码语言:javascript复制# -*- coding: UTF-8 -*-
import pandas as pd
df=pd.read_excel('名单(10单位各5).xlsx')
df['身份证']=df['身份证'].astype('str')
def split_files(x_df):
with pd.ExcelWriter(f'拆分表/{x_df.name}.xlsx')as exl:
x_df.groupby('类别').apply(
lambda x: x.to_excel(exl,x.name,index=False)
)
exl.save()
df.groupby('单位').apply(split_files)
【效果】
1. 目录中有py文件和一个总表 【名单(10单位各5).xlsx】 文件夹“拆分表”
2.拆分出来后文件夹中有一个单位一个文件
3.每个文件中内部有类型中的三个工作表
另外附上ExcelVBA的代码可用于比较
代码语言:javascript复制‘===功能:拆分总表以单位为名工作簿文件,每个工作簿中以类别为两个工作表
Sub test()
Dim r%, i%
Dim arr, brr
Dim wb As Workbook
Dim ws As Worksheet
Dim d As Object
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set d = CreateObject("scripting.dictionary")
With Worksheets("sheet1")
r = .Cells(.Rows.Count, 1).End(xlUp).Row
arr = .Range("a1:b" & r)
For i = 2 To UBound(arr)
If Not d.exists(arr(i, 1)) Then
Set d(arr(i, 1)) = CreateObject("scripting.dictionary")
End If
If Not d(arr(i, 1)).exists(arr(i, 2)) Then
Set d(arr(i, 1))(arr(i, 2)) = .Range("a1:r1")
End If
Set d(arr(i, 1))(arr(i, 2)) = Union(d(arr(i, 1))(arr(i, 2)), .Cells(i, 1).Resize(1, 18))
Next
End With
For Each aa In d.keys
Application.SheetsInNewWorkbook = d(aa).Count
Set wb = Workbooks.Add
k = 0
With wb
For Each bb In d(aa).keys
k = k 1
With Worksheets(k)
.Name = bb
d(aa)(bb).Copy .Range("a1")
End With
Next
.SaveAs Filename:=ThisWorkbook.Path & "" & aa
.Close False
End With
Next
Application.ScreenUpdating = True
MsgBox "数据拆分完毕!"
End Sub
==============
python有简单又强大的数据处理功能
=====今天学习到此====