如何通过编程将Microsoft Forms数据从Excel Online导入SQL Server?
将Microsoft Forms数据从Excel Online导入企业SQL Server的编程实现方案
方案1:Microsoft Graph API + Python脚本
这是最灵活的编程实现方式,通过Graph API读取SharePoint Online上的Excel Online数据,再写入SQL Server。
步骤1:配置Azure AD应用权限
- 在Azure门户注册一个应用,添加Files.Read.All或Sites.Read.All的应用权限(需管理员同意)
- 记录租户ID、客户端ID、客户端密钥,后续代码会用到
步骤2:读取Excel Online数据
使用Microsoft Graph SDK读取指定工作表的已用区域数据:
from msgraph import GraphServiceClient from azure.identity import ClientSecretCredential # 替换为你的实际参数 tenant_id = "your-tenant-id" client_id = "your-client-id" client_secret = "your-client-secret" drive_id = "sharepoint-library-id" file_id = "excel-file-id" worksheet_name = "Form Responses 1" # 通常Forms生成的工作表名 # 初始化Graph客户端 credential = ClientSecretCredential(tenant_id, client_id, client_secret) graph_client = GraphServiceClient(credential) # 获取工作表数据 range_result = graph_client.drives[drive_id].items[file_id].workbook.worksheets[worksheet_name].used_range.get() raw_data = range_result.value # 二维数组,第一行是表头,后续是数据行
步骤3:写入SQL Server
用pyodbc连接SQL Server并插入数据:
import pyodbc # 替换为你的SQL Server连接信息 conn_str = ( "DRIVER={ODBC Driver 17 for SQL Server};" "SERVER=your-sql-server-address;" "DATABASE=target-db;" "UID=sql-username;" "PWD=sql-password;" ) conn = pyodbc.connect(conn_str) cursor = conn.cursor() # 替换为你的目标表和字段,跳过表头行 insert_sql = "INSERT INTO FormResponses (Name, Email, SubmitTime, Response) VALUES (?, ?, ?, ?)" for row in raw_data[1:]: # 根据实际列数调整参数顺序 cursor.execute(insert_sql, row[0], row[1], row[2], row[3]) conn.commit() cursor.close() conn.close()
方案2:PowerShell脚本实现
适合熟悉PowerShell的运维场景,同样基于Graph API:
# 连接Graph API Connect-MgGraph -ClientId "your-client-id" -TenantId "your-tenant-id" -ClientSecret (ConvertTo-SecureString "your-client-secret" -AsPlainText -Force) # 读取Excel数据 $driveId = "sharepoint-library-id" $fileId = "excel-file-id" $worksheet = Get-MgDriveItemWorkbookWorksheet -DriveId $driveId -DriveItemId $fileId -WorksheetId "Form Responses 1" $rangeData = (Get-MgDriveItemWorkbookWorksheetUsedRange -DriveId $driveId -DriveItemId $fileId -WorksheetId $worksheet.Id).Value # 连接SQL Server并插入数据 $conn = New-Object System.Data.SqlClient.SqlConnection $conn.ConnectionString = "Server=your-sql-server;Database=target-db;User ID=sql-username;Password=sql-password;" $conn.Open() $cmd = $conn.CreateCommand() $cmd.CommandText = "INSERT INTO FormResponses (Name, Email, SubmitTime) VALUES (@name, @email, @time)" foreach ($row in $rangeData[1..($rangeData.Count-1)]) { $cmd.Parameters.Clear() $cmd.Parameters.AddWithValue("@name", $row[0]) $cmd.Parameters.AddWithValue("@email", $row[1]) $cmd.Parameters.AddWithValue("@time", $row[2]) $cmd.ExecuteNonQuery() } $conn.Close()
关键注意事项
- 权限验证:确保Azure AD应用有足够的SharePoint访问权限,SQL Server允许脚本所在机器的IP访问(云SQL需配置防火墙规则)
- 数据类型匹配:提前对齐Excel列与SQL表字段的数据类型,比如日期、数字格式的转换
- 增量同步优化:如果不需要全量导入,可通过Forms生成的「提交时间」列,记录上次同步时间,只导入新增数据
- 错误处理:实际部署时建议添加异常捕获逻辑,避免单次数据导入失败中断整体流程
内容的提问来源于stack exchange,提问作者Rebel7284
相关产品推荐
相关产品推荐

