使用C#借助Microsoft.SharePoint.Client从SharePoint批量下载Excel文件
Got it, here's a complete implementation using the SharePoint Client Object Model (via the Microsoft.SharePoint.Client DLL) to download all Excel files from a SharePoint site to a specified local folder. I’ll walk you through the code and break down the key bits so you can adapt it to your needs.
Prerequisites
- Install the required NuGet package:
- For SharePoint Online: Install
Microsoft.SharePointOnline.CSOM(this includes the coreMicrosoft.SharePoint.ClientDLLs) - For On-premises SharePoint: Install
Microsoft.SharePoint.ClientandMicrosoft.SharePoint.Client.Runtime
- For SharePoint Online: Install
- Ensure you have read permissions to the target SharePoint site and all its document libraries/folders
- The local target folder can be auto-created by the code (we’ve included that logic)
Full C# Code Example
using System; using System.IO; using System.Security; using Microsoft.SharePoint.Client; class SharePointExcelDownloader { static void Main(string[] args) { // Update these values to match your environment string siteUrl = "https://your-sharepoint-site-url"; string username = "your-username@domain.com"; // SPO: work/school account; On-prem: domain\username string password = "your-password"; string localDownloadFolder = @"C:\Your\Local\Download\Folder"; // Create local folder if it doesn't exist if (!Directory.Exists(localDownloadFolder)) { Directory.CreateDirectory(localDownloadFolder); Console.WriteLine($"Created local folder: {localDownloadFolder}"); } // Initialize SharePoint Client Context using (ClientContext context = new ClientContext(siteUrl)) { // Authenticate - switch between SPO and On-prem as needed context.Credentials = new SharePointOnlineCredentials(username, ConvertToSecureString(password)); // For On-prem: context.Credentials = new System.Net.NetworkCredential(username, password, "your-domain"); try { // Fetch all document libraries in the site Web web = context.Web; context.Load(web.Lists, lists => lists.Include(list => list.Title, list => list.RootFolder) .Where(list => list.BaseType == BaseType.DocumentLibrary)); context.ExecuteQuery(); foreach (List library in web.Lists) { Console.WriteLine($"\nProcessing library: {library.Title}"); // Recursively scan all folders and files in the library ProcessFolder(context, library.RootFolder, localDownloadFolder); } Console.WriteLine("\n✅ All Excel files downloaded successfully!"); } catch (Exception ex) { Console.WriteLine($"\n❌ Error occurred: {ex.Message}"); } } } private static void ProcessFolder(ClientContext context, Folder folder, string localRootFolder) { // Load folder contents (subfolders and files) context.Load(folder, f => f.Folders, f => f.Files); context.ExecuteQuery(); // Create matching local folder structure string localFolderPath = Path.Combine(localRootFolder, folder.ServerRelativeUrl.TrimStart('/').Replace('/', '\\')); if (!Directory.Exists(localFolderPath)) { Directory.CreateDirectory(localFolderPath); } // Download Excel files in current folder foreach (File file in folder.Files) { string fileExt = Path.GetExtension(file.Name).ToLower(); // Check for common Excel file types if (fileExt is ".xlsx" or ".xls" or ".xlsm" or ".xlsb") { Console.WriteLine($"Downloading: {file.Name}"); DownloadFile(context, file, localFolderPath); } } // Recursively process subfolders foreach (Folder subFolder in folder.Folders) { ProcessFolder(context, subFolder, localRootFolder); } } private static void DownloadFile(ClientContext context, File file, string localFolderPath) { // Fetch file content from SharePoint FileInformation fileInfo = File.OpenBinaryDirect(context, file.ServerRelativeUrl); // Save to local disk string localFilePath = Path.Combine(localFolderPath, file.Name); using (FileStream fs = new FileStream(localFilePath, FileMode.Create)) { fileInfo.Stream.CopyTo(fs); } } private static SecureString ConvertToSecureString(string password) { SecureString secureString = new SecureString(); foreach (char c in password) { secureString.AppendChar(c); } return secureString; } }
Key Notes & Explanations
- Authentication: We’ve included both SharePoint Online and on-prem authentication options—just comment/uncomment the relevant line. For production, avoid hardcoding passwords; use a secure credential store like Azure Key Vault instead.
- Recursive Scanning: The
ProcessFoldermethod digs through all subfolders in each document library, so you won’t miss any nested Excel files. - File Filtering: We check for the most common Excel extensions, but you can add/remove extensions (like
.xltxfor templates) as needed. - Local Structure: The code replicates the SharePoint folder hierarchy locally, so you’ll have the same organization as the original site.
- Error Handling: Basic exception catching is included—you can expand this to log errors to a file or handle specific issues like permission denials.
内容的提问来源于stack exchange,提问作者Jithin Gangadharan
相关产品推荐
相关产品推荐

