c#锁定Excel工作表和单元格

来源:互联网 发布:淘宝助理 下载宝贝 编辑:程序博客网 时间:2024/05/16 00:42
  1. publicvoidCreateExcel()

  2. {

  3. //创建一个Excel文件 

  4. Microsoft.Office.Interop.Excel.Application myExcel = newMicrosoft.Office.Interop.Excel.Application();

  5. Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;

  6. Microsoft.Office.Interop.Excel.Worksheet excelSheet = null;

  7. myExcel.Application.Workbooks.Add(true);


  8. //让Excel文件可见 

  9. myExcel.Visible = true;


  10. myExcel.Cells[1, 4] = "普通报表";


  11. //逐行写入数据 

  12. for(inti = 0; i < 11; i++)

  13. {

  14. for(intj = 0; j < 7; j++)

  15. {

  16. //以单引号开头,表示该单元格为纯文本 

  17. myExcel.Cells[2 + i, 1 + j] = "'"+ i;

  18. }

  19. }


  20. try

  21. {

  22. stringexcelTemp ="c://a.xls"


  23. //excelWorkbook = myExcel.Workbooks[1]; 

  24. excelWorkbook = myExcel.ActiveWorkbook;

  25. excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkbook.ActiveSheet;


  26. //设定允许操作的单元格 

  27. Microsoft.Office.Interop.Excel.AllowEditRanges ranges = excelSheet.Protection.AllowEditRanges;

  28. ranges.Add("Information",

  29. myExcel.Application.get_Range("B2""B2"),

  30. Type.Missing);


  31. //保护工作表 

  32. excelSheet.Protect("MyPassword", Type.Missing, Type.Missing, Type.Missing,

  33. Type.Missing, Type.Missing, Type.Missing, Type.Missing,

  34. Type.Missing, Type.Missing, Type.Missing, Type.Missing,

  35. Type.Missing, true, Type.Missing, Type.Missing);


  36. //Realease the com object 

  37. System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet);

  38. excelSheet = null;



  39. //Save the result to a temp path 

  40. excelWorkbook.SaveAs(excelTemp, Excel.XlFileFormat.xlWorkbookNormal,

  41. nullnullfalsefalse,

  42. Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing,

  43. Type.Missing, Type.Missing,Type.Missing,Type.Missing);

  44. }

  45. catch(Exception ex)

  46. {

  47. throw;

  48. }

  49. finally

  50. {

  51. if(excelWorkbook != null)

  52. {

  53. System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);

  54. excelWorkbook = null;

  55. }

  56. if(myExcel != null)

  57. {

  58. myExcel.Workbooks.Close();

  59. myExcel.Quit();

  60. System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);

  61. myExcel = null;

  62. }


  63. GC.Collect();

  64. }

  65. }



对Excel操作时,由于使用权限的不同,可能对表格的操作权限也不一样。EXCEL提供了保护工作表以及允许编辑单元格功能。相应的在C#中就可以对Excel表格进行操作。 

主要用Protect()方法保护工作表,Worksheet.Protection.AllowEditRanges设置允许编辑的单元格。


来自Wang_Zemin闲的蛋疼时候写的空间搬家工具
文章迁移自我的百度空间 o0o王泽民o0o