如何用C#为桌面已有Excel文件设置密码(不使用第三方DLL)
Got it, let's break this down into two straightforward steps—no third-party DLLs required, just using .NET's built-in libraries for both tasks.
We'll use Microsoft.Office.Interop.Excel for this, which is part of the .NET Framework's Office interop assemblies. Note: This requires Microsoft Excel to be installed on the machine running the code.
First, add a reference to Microsoft.Office.Interop.Excel in your project (you can find it under the COM tab in Visual Studio's Add Reference dialog).
Here's the code to set a password and save the file:
using Microsoft.Office.Interop.Excel; using System; class ExcelPasswordProtector { public static void ProtectExcelFile(string filePath, string password) { Application excelApp = null; Workbook workbook = null; try { // Initialize Excel application (run in background) excelApp = new Application(); excelApp.Visible = false; // Open the target workbook workbook = excelApp.Workbooks.Open(filePath); // Set password required to open the file workbook.Password = password; // Save changes and close the workbook workbook.Save(); workbook.Close(); } catch (Exception ex) { Console.WriteLine($"Error protecting Excel file: {ex.Message}"); } finally { // Clean up COM objects to avoid lingering Excel processes if (workbook != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); if (excelApp != null) { excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); } } } }
You can call this method like so (it targets your desktop file):
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string excelFilePath = $@"{desktopPath}\YourExcelFile.xlsx"; ProtectExcelFile(excelFilePath, "YourSecurePassword123!");
For this, we'll use System.Net.Mail—a fully native .NET library for email operations.
Here's the code to send the email with your protected Excel file:
using System.Net; using System.Net.Mail; class EmailSender { public static void SendEmailWithAttachment(string recipientEmail, string excelFilePath) { try { // Build the email message MailMessage mail = new MailMessage(); mail.From = new MailAddress("your-email@example.com"); mail.To.Add(recipientEmail); mail.Subject = "Password-Protected Excel Document"; mail.Body = "Please find the password-protected Excel file attached. The password is: YourSecurePassword123!"; // Attach the protected Excel file Attachment attachment = new Attachment(excelFilePath); mail.Attachments.Add(attachment); // Configure your SMTP client (update with your provider's settings) SmtpClient smtpClient = new SmtpClient("smtp.example.com", 587); smtpClient.Credentials = new NetworkCredential("your-email@example.com", "your-account-password"); smtpClient.EnableSsl = true; // Most modern providers require this // Send the email smtpClient.Send(mail); // Clean up resources attachment.Dispose(); mail.Dispose(); smtpClient.Dispose(); Console.WriteLine("Email sent successfully!"); } catch (Exception ex) { Console.WriteLine($"Error sending email: {ex.Message}"); } } }
Call this method right after protecting your Excel file:
SendEmailWithAttachment("recipient@example.com", excelFilePath);
Key Notes
- SMTP Settings: Replace
smtp.example.com, port number, and credentials with your email provider's details. For example:- Outlook/Office 365:
smtp.office365.comon port 587 - Gmail:
smtp.gmail.comon port 587 (use an app password if 2FA is enabled)
- Outlook/Office 365:
- Excel Interop Limitation: This approach requires Excel to be installed on the machine running the code. Without Excel, there's no native .NET way to manipulate Excel files—third-party libraries would be needed, but you specified avoiding those.
- COM Cleanup: Always release COM objects in the
finallyblock to prevent Excel processes from running in the background unnoticed.
内容的提问来源于stack exchange,提问作者Mayur

