您的位置:首页 > 编程语言 > C#

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

2007-04-30 00:30 831 查看
模拟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, 0, true, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true);

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

//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,
null, null, false, false,
Excel.XlSaveAsAccessMode.xlNoChange, false, false, null, null);
}
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐