Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel XLXSWriter将分组数据写入多个工作簿_Excel_Python 3.x - Fatal编程技术网

Excel XLXSWriter将分组数据写入多个工作簿

Excel XLXSWriter将分组数据写入多个工作簿,excel,python-3.x,Excel,Python 3.x,我有一个电子表格,上面有主管姓名和他们的员工。我需要按主管对数据进行分组,并为每个主管创建一个单独的电子表格,其中包含每个主管的员工和一些相关信息。我还需要格式化这些工作表和一些公式 for group_name, group in gb: group.to_excel(r'C:\PATH'.format(group_name), sheet_name = 'Review', index=False, startrow = 0) 我可以使用.to_excel创建包含分组数据的多个电子表

我有一个电子表格,上面有主管姓名和他们的员工。我需要按主管对数据进行分组,并为每个主管创建一个单独的电子表格,其中包含每个主管的员工和一些相关信息。我还需要格式化这些工作表和一些公式

for group_name, group in gb:
    group.to_excel(r'C:\PATH'.format(group_name), sheet_name = 'Review', index=False, startrow = 0)
我可以使用.to_excel创建包含分组数据的多个电子表格,但无法找到添加格式和公式的方法

for group_name, group in gb:
    group.to_excel(r'C:\PATH'.format(group_name), sheet_name = 'Review', index=False, startrow = 0)
我可以用xlxswriter创建多个工作簿,但我只能通过将数据框推到元组中来获取写入文件的数据,然后每个电子表格填充所有数据,而不是分组数据

for group_name, group in gb:
    workbook = xlsxwriter.Workbook(group_name + '.xlsx')
    worksheet = workbook.add_worksheet('Review')
    worksheet.write('A1', 'Sup Name')
    worksheet.write('B1', 'SupNo')
    worksheet.write('C1', 'Full Name')
    worksheet.write('D1', 'EENO')
    row = 1
    col = 0
    for SupName, SupNo, fullname, eeno in (tuples):
        worksheet.write_string(row, col, SupName)
        worksheet.write_number(row, col+1, SupNo)
        worksheet.write_string(row, col+2, fullname)
        worksheet.write_number(row, col+3, eeno)
        row += 1
    workbook.close()
尝试找出如何基于组创建多个工作簿,并使用分组数据。我还尝试创建元组组,但出现了一个错误,表明有太多的值需要解包


有什么建议吗?

以防有人想看它(也许这样我以后可以再找到它)。下面是我用来排序、格式化、添加公式、拆分到工作簿和锁定的宏。这一切都是拼凑在一起的,它可以工作,但它可以更高效、更干净,将来会恢复到这一点

Sub AddContentHeader()
Range("$E$1").Value = "HEADER TITLE" 'Repeat for each header needed

End Sub

Sub FormatTxtHead() 'Keeping all for the variance
Range("A1:N1").Font.Bold = True
Range("A1:N1").WrapText = True
Range("A1:N2814").Font.Size = 11 'Adjust to full data range
Range("A1:N2814").Font.Name = "Calibri" 'Adjust to full data range
Range("A1:N2814").Borders.LineStyle = xlContinuous 'Adjust to full data range
Range("A1:N1").Interior.Pattern = xlSolid
Range("K1:N1").Interior.Color = RGB(105, 139, 105) 'Green
Range("F1:G1").Interior.Color = RGB(224, 238, 224) 'Light Green
Range("I1").Interior.Color = RGB(224, 238, 224) 'Light Green
Range("A1:E1").Interior.Color = RGB(162, 181, 205) 'Blue
Range("H1").Interior.Color = RGB(162, 181, 205) 'Blue
Range("J1").Interior.Color = RGB(162, 181, 205) 'Blue
End Sub

Sub AddFormulas()
Range("G1:G2814").NumberFormat = "0.00%"
Range("I1:I2814").NumberFormat = "0.00%"
Range("H2").Formula = "=E2*G2"
Range("H2").Copy
Range("H2:H2814").PasteSpecial (xlPasteAll) 'Adjust to full data range
Range("H2:H2814").NumberFormat = "$#,##0"
Range("J2").Formula = "=E2*I2"
Range("J2").Copy
Range("J2:J2814").PasteSpecial (xlPasteAll) 'Adjust to full data range
Range("J2:J2814").NumberFormat = "$#,##0"
Range("K2").Formula = "=G2+I2"
Range("K2").Copy
Range("K2:K2814").PasteSpecial (xlPasteAll) 'Adjust to full data range
Range("K2:K2814").NumberFormat = "0.00%"
Range("L2").Formula = "=E2+H2"
Range("L2").Copy
Range("L2:L2814").PasteSpecial (xlPasteAll) 'Adjust to full data range
Range("L2:L2814").NumberFormat = "$#,##0"
Range("M2").Formula = "=L2/2080"
Range("M2").Copy
Range("M2:M2814").PasteSpecial (xlPasteAll) 'Adjust to full data range
Range("M2:M2814").NumberFormat = "$#,##0"
Range("N2").Formula = "=J2+L2"
Range("N2").Copy
Range("N2:N2814").PasteSpecial (xlPasteAll) 'Adjust to full data range
Range("N2:N2814").NumberFormat = "$#,##0"
End Sub

Sub DropDownSelectList()

'replace "F2:F2814" with the cell range you want to insert the drop down list
With Range("F2:F2814").Validation
.Delete
'replace "New,Low,Below,Met,Exceed,Super" with list or the range the validation data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="New,Low,Below,Met,Exceed,Super"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub


Sub SplitToWorksheets()
Dim ColHead As String
Dim ColHeadCell As Range
Dim iCol As Integer
Dim iRow As Long 'row index on Fan Data sheet
Dim Lrow As Integer 'row index on individual destination sheet
Dim Dsheet As Worksheet 'destination worksheet
Dim Fsheet As Worksheet 'fan data worksheet (assumed active)
Again:
ColHead = InputBox("Enter Column Heading", "Identify Column", [c1].Value)
If ColHead = "" Then Exit Sub
Set ColHeadCell = Rows(1).Find(ColHead, LookAt:=xlWhole)
If ColHeadCell Is Nothing Then
MsgBox "Heading not found in row 1"
GoTo Again
End If
Set Fsheet = ActiveSheet
iCol = ColHeadCell.Column
'loop through values in selected column
For iRow = 2 To Fsheet.Cells(65536, iCol).End(xlUp).Row
If Not SheetExists(CStr(Fsheet.Cells(iRow, iCol).Value)) Then
Set Dsheet = Worksheets.Add(after:=Worksheets(Worksheets.Count))
Dsheet.Name = CStr(Fsheet.Cells(iRow, iCol).Value)
Fsheet.Rows(1).Copy
With Dsheet.Rows(1)
    .PasteSpecial xlPasteColumnWidths
    .PasteSpecial xlPasteValues
    .PasteSpecial xlPasteFormats
End With
Else
Set Dsheet = Worksheets(CStr(Fsheet.Cells(iRow, iCol).Value))
End If
Lrow = Dsheet.Cells(65536, iCol).End(xlUp).Row
Fsheet.Rows(iRow).Copy Destination:=Dsheet.Rows(Lrow + 1)
Next iRow
End Sub

Function SheetExists(SheetId As Variant) As Boolean
' This function checks whether a sheet (can be a worksheet,
' chart sheet, dialog sheet, etc.) exists, and returns
' True if it exists, False otherwise. SheetId can be either
' a sheet name string or an integer number. For example:
' If SheetExists(3) Then Sheets(3).Delete
' deletes the third worksheet in the workbook, if it exists.
' Similarly,
' If SheetExists("Annual Budget") Then Sheets("Annual Budget").Delete
' deletes the sheet named "Annual Budget", if it exists.
Dim sh As Object
On Error GoTo NoSuch
Set sh = Sheets(SheetId)
SheetExists = True
Exit Function
NoSuch:
If Err = 9 Then SheetExists = False Else Stop
End Function


Sub InsertFormula()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
    ws.Activate
    NxtRw1 = Cells(Rows.Count, "B").End(xlUp).Row + 2
    With Cells(NxtRw1, "B")
     .Formula = "Total Pool"
     .Interior.Color = RGB(162, 181, 205) 'Blue
     .Font.Bold = True
    End With
    NxtRw2 = Cells(Rows.Count, "C").End(xlUp).Row + 2
    With Cells(NxtRw2, "C")
     .Formula = "=SUM(E1:E" & NxtRw2 - 1 & ")*.03"
     .NumberFormat = "$#,##0"
     .Font.Bold = True
    End With
    NxtRw3 = Cells(Rows.Count, "D").End(xlUp).Row + 2
    With Cells(NxtRw3, "D")
     .Formula = "Remaining"
     .Interior.Color = RGB(162, 181, 205) 'Blue
     .Font.Bold = True
    End With
    NxtRw4 = Cells(Rows.Count, "E").End(xlUp).Row + 2
    With Cells(NxtRw4, "E")
     .Formula = "=(SUM(E1:E" & NxtRw4 - 1 & ")*.03)-((SUM(N1:N" & NxtRw4 - 1 & ")-SUM(E1:E" & NxtRw4 - 1 & ")))"
     .NumberFormat = "$#,##0"
     .Interior.Color = RGB(255, 255, 0) 'Yellow
     .Font.Bold = True
    End With
Next
End Sub



Sub RemoveColumns()

Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
ws.Columns("A:A").EntireColumn.Delete 'Set to data range

Next ws
End Sub

Sub CopyPasteKey()
Dim i As Long
For Each ws In Worksheets
  With ws
  i = .Range("D" & Rows.Count).End(3).Row 'Set Range to longest column in key
  Sheets("Sheet420").Range("A1:I15").Copy .Range("A" & i + 2)
  End With
Next ws
End Sub


Sub protect_all_sheets()
top:
    pass = InputBox("password?")
    repass = InputBox("Verify Password")
    If Not (pass = repass) Then
      MsgBox "you made a boo boo"
      GoTo top
    End If

    For i = 1 To Worksheets.Count
        If Worksheets(i).ProtectContents = True Then GoTo oops
    Next

    For Each s In ActiveWorkbook.Worksheets
        s.Protect Password:=pass
    Next
    Exit Sub

oops:
    MsgBox "I think you have some sheets that are already protected. Please unprotect all sheets then run this Macro."
End Sub



Sub Split_To_Workbook()
'Working in 2013/2016
    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim Sourcewb As Workbook
    Dim Destwb As Workbook
    Dim sh As Worksheet
    Dim DateString As String
    Dim FolderName As String
    Dim myOutlook As Object
    Dim myMailItem As Object
    Dim mySubject As String
    Dim myPath As String
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
        .Calculation = xlCalculationManual
    End With


    'Copy every sheet from the workbook with this macro
    Set Sourcewb = ActiveWorkbook
    'Create new folder to save the new files in
    DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
    FolderName = "C:\PATH\" & Sourcewb.Name & " " & DateString
    MkDir FolderName
    'Copy every visible sheet to a new workbook
    For Each sh In Sourcewb.Worksheets
        'If the sheet is visible then copy it to a new workbook
        If sh.Visible = -1 Then
            sh.Copy
            'Set Destwb to the new workbook
            Set Destwb = ActiveWorkbook
            'Determine the Excel version and file extension/format
            With Destwb
                If Val(Application.Version) < 12 Then
                    'You use Excel 97-2003
                    FileExtStr = ".xls": FileFormatNum = -4143
                Else
                    'You use Excel 2007-2016
                    If Sourcewb.Name = .Name Then
                        MsgBox "Your answer is NO in the security dialog"
                        GoTo GoToNextSheet
                    Else
                        FileExtStr = ".xlsx": FileFormatNum = 51
                    End If
                End If
            End With
            'Change all cells in the worksheet to values if you want
            If Destwb.Sheets(1).ProtectContents = False Then
                With Destwb.Sheets(1).UsedRange
                    .Cells.Copy
                    .Cells.PasteSpecial xlPasteValues
                    .Cells(1).Select
                End With
                Application.CutCopyMode = False
            End If
            'Save the new workbook, email it, and close it
            With Destwb
                .SaveAs FolderName _
                      & "\" & Destwb.Sheets(1).Name & FileExtStr, _
                        FileFormat:=FileFormatNum
            End With
            myPath = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
            With Destwb
                .Close False
            End With

        End If
GoToNextSheet:
    Next sh
    MsgBox "You can find the files in " & FolderName
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
    End With
End Sub


'May want to open a new workbook to run this. You will have to accept every file
Sub YE_SetPassword()

    Dim strFile As String
    Dim strPath As String
    Dim colFiles As New Collection
    Dim i As Integer
    Dim x As String
    Dim ws As Worksheet

    strPath = "C:\Users\FOLDER\" 'UPDATE TO DESTINATION FOLDER
    strFile = Dir(strPath)

    ' Add Excel File Names to the variable colfiles
    While strFile <> ""
        colFiles.Add strFile
        strFile = Dir
    Wend

    ' Start reading colfiles collection and open workbooks one at a time
    If colFiles.Count > 0 Then
        For i = 1 To colFiles.Count
            ActiveSheet.Cells(i, 1).Value = colFiles(i)
                Application.Workbooks.Open strPath & colFiles(i)
            Workbooks(colFiles(i)).Activate

    ' Once workbook is open search for Sheet2 and Sheet3 and if they are there, delete them
    Application.DisplayAlerts = False
    Err.Clear
    On Error Resume Next
        Set ws = Sheets("Sheet2")
        ws.Delete
    Err.Clear
    On Error Resume Next
        Set ws = Sheets("Sheet3")
        ws.Delete
    Application.DisplayAlerts = True

    ' Check cell value of A2 for Sup Name the assign a password based on that value
        x = Range("A2").Value
        Select Case x
    Case "LOOKUP VALUE"
        pw = "PASSWORD TO LOCK WITH"
        End Select

        ' Save the workbook with unique password
        ActiveWorkbook.SaveAs Filename:= _
            strPath & colFiles(i), FileFormat:= _
                xlOpenXMLWorkbook, Password:=pw, WriteResPassword:="", _
                ReadOnlyRecommended:=False, CreateBackup:=False
            ActiveWorkbook.Close True
        Next i
    End If
End Sub
Sub AddContentHeader()
范围(“$E$1”)。Value=“HEADER TITLE””对所需的每个页眉重复此操作
端接头
子格式TXTHEAD()'保留差异的所有内容
范围(“A1:N1”).Font.Bold=True
范围(“A1:N1”)。WrapText=True
范围(“A1:N2814”).Font.Size=11'调整到完整数据范围
范围(“A1:N2814”).Font.Name=“Calibri”调整为完整数据范围
范围(“A1:N2814”).Borders.LineStyle=xlContinuous“调整到完整数据范围
范围(“A1:N1”)。内部模式=xlSolid
范围(“K1:N1”)。内饰。颜色=RGB(105139105)“绿色
范围(“F1:G1”).Interior.Color=RGB(224238224)浅绿色
范围(“I1”).Interior.Color=RGB(224238224)浅绿色
范围(“A1:E1”).Interior.Color=RGB(162181205)“蓝色
范围(“H1”).Interior.Color=RGB(162181205)“蓝色
范围(“J1”).Interior.Color=RGB(162181205)“蓝色
端接头
子公式()
范围(“G1:G2814”).NumberFormat=“0.00%”
范围(“I1:I2814”)。NumberFormat=“0.00%”
范围(“H2”)。公式=“=E2*G2”
范围(“H2”)。副本
范围(“H2:H2814”).PasteSpecial(xlPasteAll)”调整为完整数据范围
范围(“H2:H2814”).NumberFormat=“$#,##0”
范围(“J2”)。公式=“=E2*I2”
范围(“J2”)。复制
范围(“J2:J2814”).PasteSpecial(xlPasteAll)”调整为完整数据范围
范围(“J2:J2814”).NumberFormat=“$#,##0”
范围(“K2”)。公式=“=G2+I2”
范围(“K2”)。副本
范围(“K2:K2814”).PasteSpecial(xlPasteAll)”调整为完整数据范围
范围(“K2:K2814”)。NumberFormat=“0.00%”
范围(“L2”)。公式=“=E2+H2”
范围(“L2”)。复制
范围(“L2:L2814”).PasteSpecial(xlPasteAll)”调整为完整数据范围
范围(“L2:L2814”).NumberFormat=“$#,##0”
范围(“M2”)。公式=“=L2/2080”
范围(“M2”)。副本
范围(“M2:M2814”).PasteSpecial(xlPasteAll)”调整至完整数据范围
范围(“M2:M2814”).NumberFormat=“$#,##0”
范围(“N2”)。公式=“=J2+L2”
范围(“N2”)。副本
范围(“N2:N2814”).PasteSpecial(xlPasteAll)”调整为完整数据范围
范围(“N2:N2814”).NumberFormat=“$#,##0”
端接头
子下拉列表()
'将“F2:F2814”替换为要插入下拉列表的单元格范围
带有范围(“F2:F2814”)。验证
.删除
用列表或验证数据所在的范围“替换”新的、低的、低于的、符合的、超过的、超级的。
.Add类型:=xlValidateList,AlertStyle:=xlValidAlertStop_
运算符:=xlBetween,公式1:=“新的、低的、低的、满足的、超过的、超的”
.IgnoreBlank=True
.InCellDropdown=True
.InputTitle=“”
.ErrorTitle=“”
.InputMessage=“”
.ErrorMessage=“”
.ShowInput=True
.ror=真
以
端接头
子拆分工作表()
像线一样暗的黑头
暗淡的阴头细胞
作为整数的Dim-iCol
风扇数据表上的“长”行索引
Dim Lrow作为单个目的地工作表上的整数行索引
将数据表设置为工作表的目标工作表
将Fsheet作为工作表的风扇数据工作表(假定处于活动状态)
再一次:
ColHead=InputBox(“输入列标题”、“标识列”、[c1]。值)
如果ColHead=“”,则退出Sub
设置ColHeadCell=Rows(1)。查找(ColHead,LookAt:=xlother)
如果ColHeadCell不算什么
MsgBox“在第1行中找不到标题”
又来了
如果结束
设置Fsheet=ActiveSheet
iCol=ColHeadCell.Column
'循环浏览选定列中的值
对于iRow=2到Fsheet.Cells(65536,iCol).End(xlUp).Row
如果不存在(CStr(Fsheet.Cells(iRow,iCol.Value))则
设置Dsheet=Worksheets.Add(后面:=Worksheets(Worksheets.Count))
Dsheet.Name=CStr(Fsheet.Cells(iRow,iCol).Value)
F表.第(1)行.复制
带数据表。行(1)
.Paste特殊XLPaste柱宽
.Paste特殊XLPaste值
.Paste特殊XLPaste格式
以
其他的
设置数据表=工作表(CStr(Fsheet.Cells(iRow,iCol.Value))
如果结束
Lrow=Dsheet.Cells(65536,iCol).End(xlUp).Row
Fsheet.Rows(iRow).复制目标:=Dsheet.Rows(iRow+1)
下一步
端接头
函数SheetExists(SheetId为变量)为布尔值
'此函数用于检查工作表(可以是工作表,
'图表工作表、对话框工作表等)存在,并返回
'如果存在,则为True,否则为False。SheetId可以是
'工作表名称字符串或整数。例如:
'如果存在图纸(3),则为图纸(3)。删除
'删除工作簿中的第三个工作表(如果存在)。
"同样,,
'如果存在表格(“年度预算”),则表格(“年度预算”)。删除
'删除名为“年度预算”的工作表(如果存在)。
将sh作为对象
关于错误GoTo NoSuch
设置sh=图纸(图纸ID)
SheetExists=True
退出功能
不这样:
如果Err=9,则SheetExists=False,否则停止
端函数
子插入公式()
将ws设置为工作表
对于此工作簿中的每个ws。工作表
ws.Activate
NxtRw1=单元格(Rows.Count,“B”)。结束(xlUp)。行+2
带单元格(NxtRw1,“B”)
.Formula=“总池”
.Interior.Color=RGB(162181205)“蓝色
.Font.Bold=True
以
NxtRw2=单元格(Rows.Count,“C”)。结束(xlUp)。行+2
带单元(NxtRw2,“C”)
.Formula=“=SU