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
Related
I am using MS Excel Interop to parse information from a collection of Excel files. If one of these Excel files has restricted access, a Windows sign-in modal opens and pauses my program. I would like to skip over these files so that this modal does not appear.
My current code, with various settings to block any Excel warnings:
var application = new Microsoft.Office.Interop.Excel.Application();
application.DisplayAlerts = false;
application.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
var workbook = application.Workbooks.Open(filePath, UpdateLinks: 0, ReadOnly: true, IgnoreReadOnlyRecommended: true, Password: "fakePassword");
I encountered a similar issue with password protected Excel documents, but was able to prevent the enter password modal by setting a fake password in the .Open code above. This causes an exception to be thrown when a file is password protected, which I then catch and the program continues on to the next Excel file.
I was hoping the WriteResPassword option for the Open method would work similarly, but even if I specify this, the Windows sign in still appears.
Any help greatly appreciated!
I'm not particularly happy with this solution, but I have found a workaround for avoiding MS sign-in modals (and many other modals) prior to opening an Excel document.
Before opening the Excel document with MS Excel Interop, I conduct a "zip test" where I zip up the file into a temporary directory, attempt to extract it, and then immediately delete that directory.
private void ZipTest(string xlsxFilePath, string tempDirectoryPath)
{
try
{
Directory.CreateDirectory(tempDirectoryPath);
string zipPath = ZipFile(xlsxFilePath, tempDirectoryPath);
using (ZipArchive zip = System.IO.Compression.ZipFile.Open(zipPath, ZipArchiveMode.Update))
{
zip.ExtractToDirectory(tempDirectoryPath);
}
Directory.Delete(tempDirectoryPath, true);
}
catch (Exception ex)
{
if (Directory.Exists(tempDirectoryPath))
{
Directory.Delete(tempDirectoryPath, true);
}
throw ex; // Do whatever you want
}
}
private string ZipFile(string filePath, string destinationDirectory)
{
string fileName = Path.GetFileName(filePath);
string zipFileName = Path.ChangeExtension(fileName, ".zip");
string destinationPath = $"{destinationDirectory}\\{zipFileName}";
File.Copy(filePath, destinationPath, false);
return destinationPath;
}
Zipping and extracting the file will fail if the workbook has restricted access, is password protected, or otherwise can't be written to. This prevents the MS sign-in modal because the excel doc is never opened.
Note that this only works on xlsx files. Any xls files need to be converted to xlsx first.
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
I am using Asp.Net MVC application, Visual Studio 2013, SQL Server Data base
There is a particular location in my system's local drive i.e., c:/Files/Exim_Files/ , where a lot of excel(.xlsx) files are sitting.
I want to get the particular file from that location and save it programmatically (without Save pop up) in same location with same/different name. while saving the excel data should not be lost, file should be as it is, just I need to save/SaveAs it again.
How can I achieve this requirement?
Note that I am using Virtual Machine and inside Virtual Machine: Microsoft Office is not installed. So the code will have to work without Microsoft Office installation in the machine. I can only use Microsoft Office in my host machine.
Edit
In below code, I am using Aspose.Cells to save the Excel file from 1 location to another.
I am getting the particular File from sharedLocation in array "l_strFileUploadPath" and then checking, if the file that I am getting from user exists in shared location, then I want to save/SaveAs that
file into different location (defined in 'string str') along with entire data (say I want to import the data as well while Saving the Excel in different location).
The issue I am facing is that, the file that is getting saved in C: drive, is not saving the data which is present inside the Excel. It seems it is creating a new excel file in c: drive with same name (x-TECHNICAL_DIT_BUDV01_RV124_R01_2015_Test.xlsx) having 2 sheets.
1 is 'sheet 1' and another is 'Evaluation Warning' sheet.
How can I remove the 'Evaluation Warning' sheet and what is the method of saving the exact file (along with data) from shared drive to c: drive, as per my code.
This is the first time using Aspose.Cells to get and Save/SaveAs the file from 1 location to another.
protected void getFileAndSave()
{
string[] l_strFileUploadPath = Directory.GetFiles("//181.184.11.435/share//Temp/New folder");
foreach (var filename in l_strFileUploadPath)
{
string fileName = Path.GetFileName(filename);
string p_filename = "x-TECHNICAL_DIT_Test.xlsx"; //this is the file I am getting from user
if (fileName == p_filename)
{
//-- Using Aspose.Cells
Workbook wb = new Workbook();
Worksheet worksheet = wb.Worksheets["Sheet1"];
worksheet.Name = "Technical Data";
//Save workbook with export cell as true
OoxmlSaveOptions opts = new OoxmlSaveOptions();
opts.ExportCellName = true;
wb.Save(str + file, opts);
}
}
}
It seems for me that you just want to copy the file.
Take a look at File.Copy()
File.Copy(#"c:\excel.xsl", #"c:\other\excel.xsl");
EDIT for comment:
I think it will be hard to change app.xml metadata without just manually looking what changes are made there during save/saveAs and then trying to understand how to copy this behavior and change it programmatically inside that file.
So I have some code that creates an excel worksheet from Smartsheets and then extracts that information from the excel worksheet into SQL. Thing is the code works if I run each part seperately but if I run it at the same time it will create the table, but it won't input the data. Below I will show each part in the main program. I don't think it is necessary to show the rest of the code because as I say it works seperately.
//Make an Excel sheet from smartsheet
Smartsheet smartsheet = new Smartsheet();
long excelSmartsheetID = smartsheet.getSmartSheetID(currentWorkSheet);
smartsheet.createExcel(excelSmartsheetID);
//Extract Data From Excel into SQL
SSIS excelToSQL = new SSIS();
excelToSQL.storeSmartSheetDataToSQL();
So I am not sure what is going on here. I have put the thread to sleep for 10 seconds in between the two sections but it still doesn't work. Completely lost as to what might be the problem. I should add I am using SSIS to connect to the excel sheet and create it in SQL. Please let me know if you require more information.
It sounds like the Excel file is still open when trying to access it a second time. When an Excel file is open for writing it becomes locked which can prevent another process (in your case SSIS) from editing the file. This can be confirmed using the Smartsheet C# SDK with code like the following which never closes the file after writing to it.
// Set the Access Token
Token token = new Token();
token.AccessToken = "YOUR_TOKEN";
// Use the Smartsheet Builder to create a Smartsheet
SmartsheetClient smartsheet = new SmartsheetBuilder().SetAccessToken(token.AccessToken).Build();
BinaryWriter output = new BinaryWriter(new FileStream("c:\\file.xls", FileMode.Create));
smartsheet.Sheets().GetSheetAsExcel(8325033727682436L, output);
Console.WriteLine("Done writting");
System.Threading.Thread.Sleep(100000);
Run the above code and after it opens and writes to the file it will sleep for a very long time. While the code is sleeping you can try to manually open the Excel file and you will get a dialog like the following showing that we still have the Excel file open (from our code) even though we finished writing to it.
The solution to this issue is to close the Excel file as soon as we are done writing to it. This can be accomplished by using the close() method on the stream or with the using statement. I prefer the using statement so an example of that is below:
// Set the Access Token
Token token = new Token();
token.AccessToken = "YOUR_TOKEN";
// Use the Smartsheet Builder to create a Smartsheet
SmartsheetClient smartsheet = new SmartsheetBuilder().SetAccessToken(token.AccessToken).Build();
using (BinaryWriter output = new BinaryWriter(new FileStream("c:\\file.xls", FileMode.Create)))
{
smartsheet.Sheets().GetSheetAsExcel(8325033727682436L, output);
}
Console.WriteLine("Done writting");
System.Threading.Thread.Sleep(100000);
Now if we run the above code it will sleep at the end but this time the Excel file will not be locked since the using statement closed the file as soon as we finished writing to it.
I need to read XLTM files without opening it.
With Excel interop, i can read but it will open the file too.
The below link shows reading xlsx file with OLDB. But same wont work for XLTM.
http://codehill.com/2009/01/reading-excel-2003-and-2007-files-using-oledb/
Is there any way i can read XLTM file with out opening the file it self.
Thanks in Advance.
You can definitely use the Excel interop assembly, just set visibility and screenUpdation off like :
Microsoft.Office.Interop.Excel.Application xltmApp = new Microsoft.Office.Interop.Excel.Application();
xltmApp.Visible = false;
xltmApp.ScreenUpdating = false;
Workbook xltmBook = xltmApp.Workbooks.Open(#"C:\test.xltm");
...do stuff
Then close document properly see: http://msdn.microsoft.com/en-us/library/h1e33e36.aspx
Also if you want you can turn off dialog boxes during saving see: Trying to exit C# Excel Workbook without a dialog box.