忽隐忽现

天道酬勤

导航

【.Net】如何使用C#代码锁定Excel文件

Posted on 2007-04-30 00:30  忽隐忽现  阅读(1612)  评论(0)    收藏  举报
模拟Office工具栏中: 工具 -〉保护 -〉保护工作表   的功能
很简单,就是对Sheet组件调用 Protect 方法。

       public string CreateExcel(string xmlFile, Object dataSource)
       
{
            
string excelTemp = string.Empty;

            
//COM Object
            Excel.Application excelApp = null;
            Excel.Workbook excelWorkbook 
= null;

            
try
            
{
                excelApp 
= new Excel.Application();
                excelWorkbook 
= excelApp.Workbooks.Open(excelPath, 0true5""""false,  Excel.XlPlatform.xlWindows, ""truefalse0true);

                
//Protect the sheet
                string passWord = Guid.NewGuid().ToString();
                excelSheet.Protect(passWord, 
truetruetruetrue);

                
//Realease the com object
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet);
                excelSheet 
= null;


                
//Save the result to a temp path
                excelWorkbook.SaveAs(excelTemp, Excel.XlFileFormat.xlWorkbookNormal,
                                     
nullnullfalsefalse,
                                     Excel.XlSaveAsAccessMode.xlNoChange, 
falsefalsenullnull);
            }

            
catch (Exception ex)
            
{
                
throw;
            }

            
finally
            
{
                
if (excelWorkbook != null)
                
{
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
                    excelWorkbook 
= null;
                }

                
if (excelApp != null)
                
{
                    excelApp.Workbooks.Close();
                    excelApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                    excelApp 
= null;
                }


                GC.Collect(); 
            }


            
return excelTemp;
        }