[英]Block Excel Column using C#
我正在使用 C# 开发 Windows 窗体应用程序。 在这个应用程序中,用户将单击一个按钮,然后程序将从剪贴板复制一些列和行,并将它们粘贴到一个新的 Excel 工作簿上,用户可以在其中编辑信息。 在 Excel 中,我只想阻止一列作为 ID,以便用户可以编辑除该列之外的所有单元格,因为该列是系统生成的。 我无法让它工作。 下面是我的代码
DataObject dataObj = null;
dataGridView1.SelectAll(); // copying data to clipboard
dataObj = dataGridView1.GetClipboardContent(); //
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.DisplayFullScreen = true;
Microsoft.Office.Interop.Excel.Range CR = xlWorkSheet.get_Range("A1", "A1");
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, false);
// for example block column A only
xlWorkSheet.Range["A1"].EntireColumn.Style.Locked = true;
// protect the sheet
xlWorkSheet.Protect(Type.Missing, true, true, true,
Type.Missing, Type.Missing, true, true, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
我的问题是,在运行此代码然后取消保护工作表后,用户仍然可以编辑 A 列。有没有办法只保护 A 列不被编辑? 我使用的是 Microsoft.Office.Interop.Excel 版本 15. 和 .Net Framework 4.5.1
任何帮助都非常感谢。
在这里试试这个。 我不完全知道问题出在哪里,但这可能会有所帮助。
DataObject dataObj = null;
dataGridView1.SelectAll(); // copying data to clipboard
dataObj = dataGridView1.GetClipboardContent(); //
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.DisplayFullScreen = true;
Microsoft.Office.Interop.Excel.Range CR = xlWorkSheet.get_Range("A1", "A1");
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, false);
// for example unblock columns B - Z only
xlWorkSheet.Range("B1", "Z1").EntireColumn.Locked = false;
// protect the sheet
xlWorkSheet.Protect(Type.Missing, true, true, true,
Type.Missing, Type.Missing, true, true, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
这绝不是您所有问题的完美解决方案。 特别是因为我不太清楚您计划使用多少其他列,但是此代码将使列 A 处于锁定状态,然后使 B 到 Z 处于解锁状态。 如果您有任何其他问题,请在评论中提出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.