基于Python或Power BI实现现场服务人员未来占用率预测报告自动化方案问询
Hey there! Let's figure out how to automate that tedious field service occupancy reporting task—no more manual copy-pasting! I’ll walk you through two solid options: Python for code-based control, and Power BI for a no-code interactive approach.
If you’re comfortable writing a bit of code, Python will give you full control over the entire workflow, from data processing to report generation. Here’s a step-by-step breakdown:
Load your SAP Excel export: Use the
pandaslibrary to read in your data. First, install the required packages if you haven’t already:pip install pandas openpyxl matplotlib seabornimport pandas as pd # Replace with your actual file path df = pd.read_excel("sap_field_service_export.xlsx", engine="openpyxl")Extract month from date columns: Convert your start/end date columns to datetime format, then pull out a sortable year-month value. Adjust column names to match your Excel file (e.g., use
df.iloc[:,0]if start date is in column A).df["Start_Date"] = pd.to_datetime(df["Start_Date"]) df["Month"] = df["Start_Date"].dt.to_period("M") # Outputs format like 2024-03Aggregate man-days by your required groups: Group the data by month, work center (column G), and activity type (column J), then sum the man-days (column C).
# Replace column names with your actual Excel labels (or use index positions like df.iloc[:,6] for column G) grouped_data = df.groupby(["Month", "Work_Center", "Activity_Type"])["Man_Days"].sum().reset_index()Calculate capacity: You’ll need monthly working days (exclude weekends/holidays) and employee counts per work center.
- Option 1: Hardcode values (or store them in a separate Excel sheet for easy updates)
# Example: key = year-month, value = working days monthly_work_days = {"2024-01": 22, "2024-02": 21, "2024-03": 21} # Employee count per work center employee_counts = {"Work_Center_North": 6, "Work_Center_South": 4} # Map values to your aggregated data grouped_data["Working_Days"] = grouped_data["Month"].astype(str).map(monthly_work_days) grouped_data["Capacity"] = grouped_data["Working_Days"] * grouped_data["Work_Center"].map(employee_counts) - Option 2: Use
pandasto auto-calculate working days (requires a holiday list for accuracy)
- Option 1: Hardcode values (or store them in a separate Excel sheet for easy updates)
Generate the bar chart with trendline: Use
seabornandmatplotlibto build your visualization.import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(12, 6)) # Bar chart for man-days sns.barplot(data=grouped_data, x="Month", y="Man_Days", hue="Work_Center") # Add capacity trendline sns.lineplot(data=grouped_data, x="Month", y="Capacity", color="black", marker="o", linewidth=2, label="Total Capacity") plt.title("Field Service Occupancy Rate by Month", fontsize=14) plt.xticks(rotation=45) plt.tight_layout() # Save the chart to a file plt.savefig("occupancy_trend_chart.png")Export the final report: Save your aggregated data to a new Excel file, or use libraries like
reportlabto build a full PDF report with the chart included.
If you prefer a no-code/low-code approach with interactive, shareable reports, Power BI is perfect. It’s great for collaborating with teams and setting up automatic refreshes.
Import your SAP Excel data: Open Power BI Desktop, go to
Home > Get Data > Excel, and select your exported file. Use Power Query Editor to clean up messy data (e.g., remove empty rows, fix date formats).Create a Calendar Table: This is critical for calculating monthly working days. Go to
Modeling > New Tableand use this DAX formula:Calendar = ADDCOLUMNS( CALENDAR(DATE(2023,1,1), DATE(2024,12,31)), "Month", FORMAT([Date], "YYYY-MM"), "IsWorkingDay", IF(WEEKDAY([Date],2) <=5, TRUE(), FALSE()) )Note: Add a company holiday list table and update the
IsWorkingDaylogic if you need to exclude holidays.Calculate aggregated man-days: Create a DAX measure to sum man-days:
Total Man Days = SUM('YourDataTable'[Man_Days])Calculate capacity: First, create or import a table with employee counts per work center. Then build this DAX measure:
Monthly Capacity = VAR CurrentMonth = MAX('Calendar'[Month]) VAR WorkingDays = CALCULATE(COUNTROWS('Calendar'), 'Calendar'[Month] = CurrentMonth, 'Calendar'[IsWorkingDay] = TRUE()) VAR EmpCount = MAX('EmployeeCounts'[Employee_Count]) RETURN WorkingDays * EmpCountBuild the visualization:
- Insert a
Clustered Column Chart - Drag
Monthfrom the Calendar table to the X-axis - Drag
Total Man Daysto the Y-axis - Drag
Work Centerto the Legend to split bars by location - Add the capacity trendline: Go to
Analytics > Trendline > Add, then set the value toMonthly Capacity(adjust the chart type to combine columns and lines if needed)
- Insert a
Set up automatic refreshes: If your SAP Excel export is stored in a shared drive or SharePoint, publish the report to Power BI Service and configure a refresh schedule. The report will update automatically whenever the source file changes.
Both solutions will eliminate that manual grind. Python is ideal if you need end-to-end automation (e.g., scheduling weekly runs) or custom reporting logic. Power BI shines for creating interactive, team-friendly reports that non-technical users can navigate.
内容的提问来源于stack exchange,提问作者Jose Vinicius

