Good day!
Currently the code to open excel file is:
public void LoadExcelFile(string fullPath)
{
using (var fileStream = File.OpenRead(fullPath))
{
_workbook = WorkbookFactory.Create(fileStream);
}
}
One of the files that I need to open now is password protected.
How can I send in a password to open the file?
Using NPOI version 2.3.0.0
Thank you in advance!
Found a solution:
As mentioned above, NPOI does not cater for a file with a password.
So I added a reference through NuGet to EPPlus and calling it as follows:
public void LoadExcelFile(string fullPath, string password)
{
var file = new FileInfo(fullPath);
var _workbook = new OfficeOpenXml.ExcelPackage(file, "password").Workbook;
}
Using it in OutSystems to load Excel files with various formats.
Related
My application needs to save a byte[] to disk, the issue is that I know it is an excel file but not what the correct file extension is. Is there a way I can tell if the file is .xls or .xlsx or .xlsm from the data itself?
I ended up writing an extension method to determine the excel file type. This method is not perfect. It will only correctly detect a .xlsm file if the file has a macro.
private static string FindType(this byte[] file)
{
using(MemoryStream ms = new MemoryStream(file))
{
var zf = new ZipArchive(ms, ZipArchiveMode.Read);
if (zf.Entries.Any(e=>e.FullName.StartsWith("xl.")))
{
if (zf.Entries.Any(e=>e.FullName.Equals("xl/vbaProject.bin", StringComparison.InvariantCultureIgnoreCase)))
return ".xlsm";
else
return ".xlsx";
}
}
return string.Empty;
}
i am working in nopcommerce solution 3.90, while importing products,
from excel file i get this exception. my code is as follow
public virtual void ImportProductsFromXlsx(Stream stream)
{
try
{
#region Import business Logic
using (var xlPackage = new ExcelPackage(stream))
{
//get the first worksheet in the workbook
var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
if (worksheet == null)
throw new NopException("No worksheet found");
//the columns
var properties = GetPropertiesByExcelCells<Product>
(worksheet);
var manager = new PropertyManager<Product>
(properties);
var attributProperties = new[]
.....
.....
}
}
StackTrace:-
at OfficeOpenXml.Utils.CompoundDocument.ILockBytes.WriteAt(Int64
ulOffset, IntPtr pv, Int32 cb, UIntPtr& pcbWritten) at
OfficeOpenXml.Utils.CompoundDocument.GetLockbyte(MemoryStream stream)
at OfficeOpenXml.ExcelPackage.Load(Stream input, Stream output, String
Password) at OfficeOpenXml.ExcelPackage.Load(Stream input) at
OfficeOpenXml.ExcelPackage..ctor(Stream newStream) at
Nop.Services.ExportImport.ImportManager.ImportProductsFromXlsx(Stream
stream) in
d:\Arsh\nop3.90\Libraries\Nop.Services\ExportImport\ImportManager.cs:line
330
Solutions That i have tried are :-
Resaving the file to be uploaded using .xlsx extension.
Using Memorystream object.
Adding name of file like(Worksheets.Add("Worksheet Name");)
Removing header text(i.e. header columns like Name, description, etc)
P.S. I am using Nopcommerce. This is inbuilt code of importing
products.
Please try with excel 2010+ because earlier versions of excel differ in encrypt/decrypt algorithm.
You can read more about encryption/decryption here.
When I download .docx file that contains 'Drawing Canvas' from VSTS with WebClient then downloaded .docx document is broken.
When I said broken, I mean that we cannot manually open Word document and we have next error message:” The file is corrupt and cannot be opened”.
This is only happening if word file contains canvas and if is downloaded from VSTS ?!
If I download from TFS2017 or if .docx file does not contains Canvas than everything is working.
Firstly, I was thinking that issue is related to Encoding, so I tested all encodings that I’ve found inside of WebClient.
Making any change related to Encoding didn’t resolve current issue.
Also, I’ve tried to change implementation in a way that we don’t use method DownloadFile and instead of that, I downloaded array of bytes and based on bytes generated Word document.
With that change in implementation, we’ve the same issue as before.
This is code example:
static void Main(string[] args)
{
var tfsUri = new Uri("https://.../");
var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri);
var workItemStore = projectCollection.GetService<WorkItemStore>();
var workItem = workItemStore.GetWorkItem(2);
projectCollection.EnsureAuthenticated();
var credentials = workItemStore.TeamProjectCollection.Credentials;
var fileName = "D:\\test_folder\\files\\System.Description.docx";
var uri = workItem.Attachments[0].Uri;
using (var request = new WebClient() { Credentials = credentials })
{
request.DownloadFile(uri, fileName);
}
}
Thank you for your help if you have any idea.
This issue was not caused by the canvas in the docx file. The file should be corrupted even there is only text in your docx file if you download it from VSTS with your code.
The issue here is that the authentication to VSTS is different with TFS, so the WebClient download file request is actually getting 401 when download the file since it don't have required permission to download the file. Update your code to following and then try again:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Proxy;
using System.IO;
namespace GetAdmin
{
class Program
{
static void Main(string[] args)
{
TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri("https://xxx.visualstudio.com/"));
ttpc.EnsureAuthenticated();
WorkItemStore wistore = ttpc.GetService<WorkItemStore>();
WorkItem wi = wistore.GetWorkItem(111);
WorkItemServer wiserver = ttpc.GetService<WorkItemServer>();
string tmppath = wiserver.DownloadFile(wi.Attachments[0].Id);
string filename = #"D:\test\test.docx";
File.Copy(tmppath,filename);
}
}
}
I am getting a error while opening using a presentation (PPTX files) creation code.
Code i am using is given below:
public static void UpdatePPT()
{
const string presentationmlNamespace = "http://schemas.openxmlformats.org/presentationml/2006/main";
const string drawingmlNamespace = "http://schemas.openxmlformats.org/drawingml/2006/main";
string fileName = Server.MapPath("~/PPT1.pptx"); //path of pptx file
using (PresentationDocument pptPackage = PresentationDocument.Open(fileName, true))
{
} // Using pptPackage
}
and the error i am getting is:
"The document cannot be opened because there is an invalid part with an unexpected content type.
[Part Uri=/ppt/printerSettings/printerSettings1.bin],
[Content Type=application/vnd.openxmlformats-officedocument.presentationml.printerSettings],
[Expected Content Type=application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings]."
error occurs at using (PresentationDocument pptPackage = PresentationDocument.Open(fileName, true))
Code works fine for many PPTX files. But it is throwing this error on some files.
I am not able to find any solution.
Thanks for your help.
Old post, but I ran in to the same problem. I solved it programatically.
Means:
My code runs using (var document = PresentationDocument.Open(fileName, true))
If this run into a exception I have a document like described. Then I call FixPowerpoint() method and do the other stuff after again.
Here is the method to share (using System.IO.Packaging):
private static void FixPowerpoint(string fileName)
{
//Opening the package associated with file
using (Package wdPackage = Package.Open(fileName, FileMode.Open, FileAccess.ReadWrite))
{
//Uri of the printer settings part
var binPartUri = new Uri("/ppt/printerSettings/printerSettings1.bin", UriKind.Relative);
if (wdPackage.PartExists(binPartUri))
{
//Uri of the presentation part which contains the relationship
var presPartUri = new Uri("/ppt/presentation.xml", UriKind.RelativeOrAbsolute);
var presPart = wdPackage.GetPart(presPartUri);
//Getting the relationship from the URI
var presentationPartRels =
presPart.GetRelationships().Where(a => a.RelationshipType.Equals("http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings",
StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
if (presentationPartRels != null)
{
//Delete the relationship
presPart.DeleteRelationship(presentationPartRels.Id);
}
//Delete the part
wdPackage.DeletePart(binPartUri);
}
wdPackage.Close();
}
}
Finally i have solved my problem. The PPTX i got was developed in mac os. So what i did is i just opened a working pptx file. And copied all the contents of not working pptx into working pptx and saved it by the name of not working pptx.
I am trying to get a method that uses the DotNetZip library to extract a file to the current working directory, although I can't seem to get it to do it, it wants a file path:
private void unzipfiles()
{
using (var zip = Ionic.Zip.ZipFile.Read("ccsetup307.zip"))
{
zip.ExtractAll("directory-name",ExtractExistingFileAction.OverwriteSilently);
}
}
If you want to extract to the current directory, why don't you use the GetCurrentDirectory method and pass that in as the expected parameter like so:
using (var zip = Ionic.Zip.ZipFile.Read("ccsetup307.zip"))
{
zip.ExtractAll(Directory.GetCurrentDirectory()
,ExtractExistingFileAction.OverwriteSilently);
}
http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory.aspx
I know it isn't implicit but it should work fine for you.
You can use the below code as well.
string x = "your file name";
using (ZipFile zip = ZipFile.Read(x))
{
zip.ExtractAll(Path.GetDirectoryName(x), ExtractExistingFileAction.OverwriteSilently);
}