密码保护C#中的Excel文件

有谁知道这个语法? 我一直在寻找,我能find的就是C ++代码。 我正在尝试使用System.IO.Packaging命名空间以编程方式密码保护excel文件。

有任何想法吗?

补充笔记:

我不使用Excel互操作,而是使用System.IO.Packaging命名空间来encryption和密码保护excel文件。

如果你想要一个Excel密码,你需要的是这样的:

using Microsoft.Office.Interop.Excel //create your spreadsheet here... WorkbookObject.Password = password; WorkbookObject.SaveAs("spreadsheet.xls") 

这需要安装Excel。

这与System.IO.Packaging无关当然,所以你可能需要重申你的问题…

您将不得不在Worksheet上使用SaveAs方法。 它有一个参数来设置密码。 这里是一个例子,在VB中可以转换为C#

http://www.codeproject.com/KB/office/Excel_Security.aspx

 using System.IO; using Excel=Microsoft.Office.Interop.Excel; class ExcelUtil { public string Filename; private Excel.Application oexcel; private Excel.Workbook obook; private Excel.Worksheet osheet; public void createPwdExcel() { try { // File name and path, here i used abc file to be // stored in Bin directory in the sloution directory //Filename = (AppDomain.CurrentDomain.BaseDirectory + "abc.xls"); if (File.Exists(Filename)) { File.Delete(Filename); } if (!File.Exists(Filename)) { // create new excel application Excel.Application oexcel = new Excel.Application(); oexcel.Application.DisplayAlerts = false; obook = oexcel.Application.Workbooks.Add(Type.Missing); oexcel.Visible = true; Console.WriteLine("Generating Auto Report"); osheet = (Excel.Worksheet)obook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing); osheet.Name = "Test Sheet"; osheet.get_Range("A1:G1").Merge(); osheet.get_Range("A1").Value = @"Implementing Password Security on Excel Workbook Using Studio.Net"; osheet.get_Range("A1").Interior.ColorIndex = 5; osheet.get_Range("A1").Font.Bold = true; string password = "abc"; obook.WritePassword = password; obook.SaveAs("Chandra.xlsx"); // otherwise use the folowing one // TODO: Labeled Arguments not supported. Argument: 2 := 'password' // end application object and session osheet = null; obook.Close(); obook = null; oexcel.Quit(); oexcel = null; } } catch (Exception ex) { } } } 

这是不可能的使用System.IO.Packaging 。 您将不得不使用Worksheet.SaveAs方法使用Microsoft.Office.Interop.Excel 。 这需要将Excel安装在目标系统上。