Password Protected Excel Download using EPPLUS - c#

I am exporting data in Excel form using EPPLUS Excel Library. I want that when excel downloaded it will ask for password. I have tried following code.
FileInfo newFile = new FileInfo("sample.xlsx");
using (ExcelPackage package = new ExcelPackage(newFile)
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add("demo");
ws.Cells[A1].LoadFromDataTable(dataTable, false);
package.Workbook.Protection.SetPassword("EPPLUS");
package.Save();
}

Just need to use the .Save overload with a password as the option:
package.Save("password");
Response To Comments
To apply a password if saving via a byte array it is very similar:
Byte[] bin = pck.GetAsByteArray("password");
System.IO.File.WriteAllBytes(fullFilePath, bin);

It's not documented, but you can do as following:
package.Encryption.Password = "your password here";
Then serve your package with Save() or GetAsByteArray() of your choice

If you are saving the excel package into a MemoryStream (for sending as an email attachment) you have to do this:
excelPackage.SaveAs(memoryStream, "pa$$w0rd");

package.GetAsByteArray("sometest"); ---> this will protect your excel sheet with password sometest :)

Related

Open workbook in Interop.Excel from byte array

I want to open Excel from byte[] because my file is encrypted and I want to open after decrypt but without write in a file.
The office has "restricted access" and I want to open my file with this protection but without saving the decrypted content in a file.
myApp.Workbooks.Open only supports a path.
Is it possible?
As an alternative to OpenXml there's also ExcelDataReader which from my experience is a lot faster in processing data compared to Interop.Excel(around 3 times+).
It can also open encrypted Excel files directly(stackoverflow)
The github page for ExcelDataReader has some great examples on how to use it. The only thing you'd have to do is:
This:
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
Becomes this:
using (var stream = new MemoryStream(yourByte[])
And if you just want to open the password protected excel file you'd do this:
var conf = new ExcelReaderConfiguration { Password = "yourPassword" }; //Add this
excelReader = ExcelReaderFactory.CreateReader(stream, conf); //change the excel Reader to this
Make sure to check the Github page for more info!
It is not possible because the interop is actually an interface for programs to run and operate existing excel on the computer.
I think you need to use openxml created by Microsoft to work with excel word and PowerPoint.
DocumentFormat.OpenXml
Then you can use:
ExcelPackage excelPackage = new ExcelPackage(stream)
or
var pck = new OfficeOpenXml.ExcelPackage();
pck.Load(File.OpenRead(path));
pck.Load(Stream) can use any stream as input not only from a file.
It depends on your needs.

Save Excel as PDF

I open an Excel file in c#, make some changes and I want to save it as pdf file.
I have searched about it and find this:
Microsoft.Office.Interop.Excel._Workbook oWB;
oWB.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, "D:\\xxxxx.pdf");
but this code sometimes opens a form and a printer must be selected! I don't know why?!
Is there any other way for exporting PDF from Excel?
I saw that Workbook.saveas() has a Fileformat object. How can we use it?
Check out Spire.Xls, below is the code for converting Excel to PDF.
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
//If you want to make the excel content fit to pdf page
//workbook.ConverterSetting.SheetFitToPage = true;
workbook.SaveToFile("result.pdf", Spire.Xls.FileFormat.PDF);
It has a free version which you can use without charge:
https://www.e-iceblue.com/Introduce/free-xls-component.html (Also available on NuGet)
Use iTextSharp. It is native .NET code. Doesn't require any Excel interop -
https://www.nuget.org/packages/itextsharp/
If you're looking for an alternative approach, then check out GemBox.Spreadsheet:
https://www.nuget.org/packages/GemBox.Spreadsheet/
Here is how you can save Excel to PDF with it:
ExcelFile excel = ExcelFile.Load("D:\\xxxxx.xlsx");
excel.Save("D:\\xxxxx.pdf");
Or you can write it as following:
XlsxLoadOptions loadOptions = new XlsxLoadOptions();
ExcelFile excel = ExcelFile.Load("D:\\xxxxx.xlsx", loadOptions);
PdfSaveOptions saveOptions = new PdfSaveOptions();
excel.Save("D:\\xxxxx.pdf", saveOptions);
You can do this using this API. Please see documentation for further detail.
http://cdn.bytescout.com/help/BytescoutPDFExtractorSDK/html/55590148-5bef-4338-ac16-1de4056a952b.htm

Using password to write to Excel File using Epplus (C#)

I am using Epplus to write to an Excel File in a web application.
The Excel file is password protected and is locked for editing (or doing anything else).
The issue arises as I am not required to use a password to write to Excel File.
Is this normal behavior?
Here is my code for accessing the protected file.
To open the existing worksheet I use this:
ExcelWorksheet ws = pck.Workbook.Worksheets["fileName"];
ws.Protection.IsProtected = false; // No password required which concerns me
How I protect it before I close it:
ws.Protection.SetPassword("myPassword");
ws.Protection.IsProtected = true;
ws.Protection.AllowSelectUnlockedCells = false;
ws.Protection.AllowSelectLockedCells = false;
When I open the file the protection is there, I cannot make changes without using the password.
Do you guys have any ideas on what is going on?
Thanks in advance

how can we convert word to .pdf format and excel to .pdf format from c#

How can we convert the excel file and word file to .pdf format from c#. i tried the following code but it shows the an error
this is my code:
Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
wordDocument = appWord.Documents.Open(#"C:\Users\ITPro2\Documents\test.docx");
wordDocument.ExportAsFixedFormat(#"D:\desktop\DocTo.pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
and i got the following Error
The export failed because this feature is not installed. during export to pdf from word from c#
While not directly related the documentation under
https://msdn.microsoft.com/en-us/library/office/ff198122.aspx
gives a note, that if the pdf add-in is not installed, exactly this error will occur. So check your prerequisites, i.e. Office installed and the add-in, too.
1) Excel 2013 Primary Interop Assembly Class Library and it works perfectly fine under .NET 4.5.1 Just add Microsoft.Office.Interop.Excel assembly to your references and you are ready to go.
using System;
using Microsoft.Office.Interop.Excel;
namespace officeInterop
{
class Program
{
static void Main(string[] args)
{
Application app = new Application();
Workbook wkb = app.Workbooks.Open("d:\\x.xlsx");
wkb.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, "d:\\x.pdf");
}
}
}
OR
2) refer this link to convert DOC or DOCx file into PDF
http://www.rasteredge.com/how-to/csharp-imaging/pdf-convert-word-to-pdf/
Since my other comment got deleted, here is the updated version.
For converting my files to pdf in c# i used the metamorphosis libary, this could also be a solution for you.
Below is a code example from me where i used a blobstorage to download PDF files from regular files.
var converter = new SautinSoft.PdfMetamorphosis();
var ms = new MemoryStream();
await blob.DownloadToStreamAsync(ms);
ms.Seek(0, SeekOrigin.Begin);
var pdfStream = converter.DocxToPdfConvertStream(ms);
if (pdfStream != null)
{
await _storageProvider.SaveFileAsync(containerName, fileName, pdfStream);
}
ms.Close();
var result = await _storageProvider.GetFileWithAttributesAsync(containerName, fileName);
return new ServiceResponse<CloudBlockBlob>(result);
Below i posted some links with the sample code from the library itself:
Word to PDF example
Excel to PDF example

Open excel with EPPlus without saving to file

Rright now I'm opening excel using
System.Diagnostics.Process.Start(fileInfo);
to open my package after saving it to a file.
Is it possible to open excel without having to save the file to a location? I would like the user to decide whether or not to save the file.
If you're generating the file yourself using EPPlus (or any other libraries that generate the file directly), you'll need to save it before you can open it in Excel. I'd recommend just saving it in the temp directory, then showing it to the user and letting them choose what to do with it.
If you generate the file using Office Automation, you can display it to the user before saving it.
I think this answer will help new developer.
I think best option for viewing Excel without saving is Microsoft.Office.Interop.Excel
Open Nuget Package Console Install-Package Microsoft.Office.Interop.Excel
create Excel file here is the official documentation Excel
at the end of filling Excel file just type app.Visible = true; app is the object name
I know this is late, but I had the same issue.
I used to use Microsoft.Office.Interop.Excel to export data to an xlsx file without saving it. It would present itself nicely as Book1.xlsx to the end-user who could them save it or close it without saving as required.
I have also moved to EPPlus to improve the speed of my exports and therefore, as you have experienced, cannot present the open file to the end-user without it first being saved.
The approach I have taken, using the SaveFileDialog component is to prompt the user for a name before the EPPlus file is created. This at least allows the end-user to identify where the file should be saved, rather than using a 'hard-coded' directory.
Private Sub btnExportXlsxEPPlus_Click(sender As Object, e As EventArgs) Handles btnExportXlsxEPPlus.Click
Try
Dim filInf As FileInfo = New FileInfo(GetFileToSave())
Using excelPackage As ExcelPackage = New ExcelPackage
excelPackage.Workbook.Properties.Author = "enLIGHTen"
excelPackage.Workbook.Properties.Title = "enLIGHTen Report"
excelPackage.Workbook.Properties.Subject = "enLIGHTen export data"
excelPackage.Workbook.Properties.Created = Date.Now
Dim worksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1")
worksheet.Cells("A1").Value = "My EPPlus spreadsheet!"
worksheet.Cells(1, 2).Value = "This is cell B1!"
excelPackage.SaveAs(filInf)
End Using
Using excelPackage As ExcelPackage = New ExcelPackage(filInf)
Dim firstWorksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets(1)
Dim namedWorksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets("SomeWorksheet")
Dim anotherWorksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets.FirstOrDefault(Function(x) x.Name Is "SomeWorksheet")
Dim valA1 As String = firstWorksheet.Cells("A1").Value.ToString
Dim valB1 As String = firstWorksheet.Cells(1, 2).Value.ToString
excelPackage.Save()
End Using
Dim proc As Process
Try
proc = New Process()
Process.Start(filInf.FullName)
Catch ex As Exception
MsgBox("File cannot be opened", MsgBoxStyle.Information, "Cannot open file")
End Try
Catch
End Try
End Sub
Public Function GetFileToSave()
Dim strFilename As String = ""
SaveFileDialog1.Filter = "Excel Workbook (*.xlsx)|*.xlsx"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
strFilename = SaveFileDialog1.FileName
Return strFilename
End If
End Function

Categories