模拟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;
}
很简单,就是对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;
}

浙公网安备 33010602011771号