You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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.

Step 1: Password-Protect Your Excel File

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!");
Step 2: Send the Protected Excel as an Email Attachment

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.com on port 587
    • Gmail: smtp.gmail.com on port 587 (use an app password if 2FA is enabled)
  • 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 finally block to prevent Excel processes from running in the background unnoticed.

内容的提问来源于stack exchange,提问作者Mayur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:08:11