Not able to Encrypt Xlsx File

Hello ,

I am using evalution copy for Aspose.cells.dll. I want to encrypt Excel file using this dll. I able to encrypt xls file successfully. But i unable to encrypt xlsx file . It gives error while opening xlsx file.

"Excel cannnot open the file “filename” because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."


I use following method to encrypt file.

string strFilePath = fuFile.PostedFile.FileName;

Workbook workbook = new Workbook(fuFile.FileContent);

workbook.SetEncryptionOptions(EncryptionType.StrongCryptographicProvider, 128);
//Password protect the file.
workbook.Settings.Password = "232"

var memoryStream = new MemoryStream();
memoryStream = workbook.SaveToStream();

–Mayur

Hi Mayur,

Thanks for your posting and using Aspose.Cells.

Please do not use workbook.SaveToStream() method because it saves to XLS format only. If you want to save in other formats like XLSX then use workbook.Save() method.

So, please change your following code

var memoryStream = new MemoryStream();
memoryStream = workbook.SaveToStream();

into this

var memoryStream = new MemoryStream();
workbook.Save(memoryStream, SaveFormat.Xlsx);
memoryStream.Position = 0;

and it will fix your issue.

Hi Shakeel,

Is this code work for both Xls and xlsx ? or i need to conditionally code for xls and xlsx?

–Mayur

Hi,


Well, you may change the line of code for XLS file format (you got to change the SaveFormat enum accordingly) i.e.,
var memoryStream = new MemoryStream();
workbook.Save(memoryStream, SaveFormat.Xlsx);
memoryStream.Position = 0;

with:

var memoryStream = new MemoryStream();
workbook.Save(memoryStream, SaveFormat.Excel97To2003);
memoryStream.Position = 0;

Hope, this helps.

Thank you.