using System;
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
static void Main()
{
// 创建Excel应用程序实例
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = null;
Excel.Worksheet worksheet = null;
try
{
// 打开一个现有的Excel文件
string filePath = @"C:\path\to\your\file.xlsx"; // 替换为你的文件路径
workbook = excelApp.Workbooks.Open(filePath);
// 获取第一个工作表
worksheet = (Excel.Worksheet)workbook.Sheets[1];
// 解锁所有单元格(默认情况下,单元格是可编辑的)
Excel.Range allCells = worksheet.UsedRange;
allCells.Locked = false;
// 锁定特定单元格(例如A1)
Excel.Range cellToLock = worksheet.Range["A1"];
cellToLock.Locked = true;
// 保护工作表
worksheet.Protect(Password: "yourPassword", // 设置密码
UserInterfaceOnly: true, // 允许用户界面操作
AllowFormattingCells: true, // 允许格式化单元格
AllowFormattingColumns: true,
AllowFormattingRows: true);
Console.WriteLine("工作表已保护,A1单元格已锁定。");
}
catch (Exception ex)
{
Console.WriteLine("发生错误:" + ex.Message);
}
finally
{
// 保存并关闭工作簿
if (workbook != null)
{
workbook.Save();
workbook.Close();
}
// 退出Excel应用程序
if (excelApp != null)
{
excelApp.Quit();
}
// 释放COM对象
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
}
}