本篇文章Effortlessly Upload PySpark DataFrames to SharePoint as CSV or Excel Files适合数据工程师和分析师,特别是那些需要将大数据结果与业务团队共享的人。文章的亮点在于通过简单的代码示例,展示了如何将PySpark DataFrame导出为CSV或Excel文件,并上传到SharePoint,解决了数据处理与业务需求之间的鸿沟。

关联Pyspark文章:



数据工程与 SharePoint 集成

一份面向数据工程师和分析师的指南,介绍如何将大数据管道与 SharePoint 集成,实现无缝协作

在企业数据工程领域,PySpark 等工具在处理大规模数据转换方面占据主导地位。但当需要将结果交付给业务干系人时,他们仍然习惯使用 Excel 和 SharePoint。

那么,我们如何弥合这一差距呢?

在本文中,我将引导你了解如何创建 PySpark DataFrame 并将其导出为 .csv.xlsx 文件,然后将其上传到 SharePoint 站点。无论你是要自动化报告还是促进协作,此设置都将使你的工作更加轻松。

1. 创建 PySpark DataFrame

首先,让我们创建一个简单的 PySpark DataFrame。如果你正在使用 Databricks 或任何 Spark 环境,这应该会很熟悉:

data = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
columns = ["Name", "Age"]

df = spark.createDataFrame(data, columns)
df.show()

2. 将 DataFrame 保存为文件

现在我们有了 DataFrame,让我们将其以所需格式保存到本地。

2.1 选项 A: 保存为 CSV

output_path = "/dbfs/tmp/people.csv"
df.coalesce(1).write.option("header", "true").mode("overwrite").csv(output_path)

Spark 会将文件保存在一个文件夹中,并将其命名为类似 part-00000.csv 的名称。如果你在 Databricks 上,请使用 dbutils 来定位和重命名它。

2.2 选项 B: 转换为 Pandas 并保存为 Excel

import pandas as pd

pandas_df = df.toPandas()

excel_path = "/dbfs/tmp/people.xlsx"
pandas_df.to_excel(excel_path, index=False)

3. 使用 Microsoft Graph API 获取 SharePoint 访问权限

要将文件上传到 SharePoint,我们将使用 Microsoft Graph API。首先,注册一个 Azure AD 应用并授予它以下权限:

  • Sites.ReadWrite.All
  • Files.ReadWrite.All

一旦你获得了 客户端 ID (client ID)客户端密钥 (client secret)租户 ID (tenant ID),请使用以下代码进行身份验证并获取访问令牌:

import requests

def get_access_token(client_id, client_secret, tenant_id):
    url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
    data = {
        'grant_type': 'client_credentials',
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': 'https://graph.microsoft.com/.default'
    }
    r = requests.post(url, data=data)
    return r.json().get('access_token')

4. 将文件上传到 SharePoint

假设你已经有了站点 URL 和文档库/文件夹路径。

import os

def upload_to_sharepoint(access_token, site_id, drive_id, folder_path, file_path):
    file_name = os.path.basename(file_path)
    upload_url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{drive_id}/root:/{folder_path}/{file_name}:/content"
    with open(file_path, 'rb') as f:
        file_content = f.read()
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/octet-stream'
    }
    response = requests.put(upload_url, headers=headers, data=file_content)
    return response.status_code, response.json()

你需要使用 Graph API 调用来检索 site_iddrive_id,例如:

  • /sites?search=your-site-name
  • /sites/{site-id}/drives

5. 额外福利:从 PySpark 触发 Power Automate Flow 运行 Excel 脚本

想不仅仅是上传文件吗?如何从 PySpark 中触发 Excel,使用 Office 脚本自动清理、刷新或计算数据呢?

以下是如何通过从 PySpark 管道调用 Power Automate flow 来自动化上传后的 Excel 操作。🚀

Power Automate Flow

5.1 步骤 1: 创建 Power Automate Flow

  1. 前往 Power Automate 并创建一个新的 flow(云端 flow → “当收到 HTTP 请求时”)。
  2. 添加一个步骤:运行脚本 (Microsoft Excel Online (Business))。
  3. 从你的 SharePoint 文档库中选择 Excel 文件
  4. 选择你在 Excel 中编写的脚本(例如清除行、应用筛选器、格式化等)。
  5. 保存你的 flow 并复制 Power Automate 在触发步骤中提供的 HTTP POST URL

5.2 步骤 2: 在 Excel 中测试你的 Office 脚本

在 Excel Online(连接到 SharePoint)中:

  • 前往 自动化新建脚本
  • 编写并保存你的脚本。示例:
function main(workbook: ExcelScript.Workbook) {
  const sheet = workbook.getWorksheet("Sheet1");
  sheet.getRange("A2:Z1000").clear();
}

5.3 步骤 3: 从 PySpark 调用 Flow (使用 Python)

上传文件后,你可以使用 Python HTTP POST 调用来触发 flow:

import requests

flow_url = "https://prod-XX.westus.logic.azure.com:443/workflows/your-flow-id/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers..."

payload = {
    "filename": "people.xlsx",
    "sheet": "Sheet1"
}
headers = {
    "Content-Type": "application/json"
}
response = requests.post(flow_url, headers=headers, json=payload)
print("Flow triggered:", response.status_code, response.text)

6. 结果:一键上传 + 自动化

通过此设置,你的 PySpark 作业可以:

  1. 将数据上传到 SharePoint。
  2. 通过 Power Automate 立即在 Excel 中运行任何脚本。

这非常适合以下工作流程:

  • 刷新数据透视表
  • 通过 Office 脚本运行宏
  • 清理旧数据
  • 当新数据到达时通过 Teams/Outlook 通知团队

7. 总结

将 PySpark 与 SharePoint 集成可能看起来像水火不容——但有了正确的“粘合剂”(Microsoft Graph API),它就能完美运行。这使得你的 Spark 驱动的洞察能够触达业务用户常用的平台:Excel 和 SharePoint。

现在你可以:

  • 自动化报告
  • 分发转换后的数据集
  • 支持协作工作流程

只需几行代码即可实现。

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐