I'm working on an Excel add-in using C# and .NET 4.0. In Excel there's a feature in the Save-As dialog for saving a preview thumbnail along with the document. How can I access this feature in code? Also, how do I access the preview image (I think it's a bitmap) once it has been saved?
Currently my Excel add-in makes a copy of the document as follows:
Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs("tempwbcopy");
It then copies the document to a server and erases the temp file. Basically I'd like to also make the thumbail image, post it to the server, and erase the temp file.
I don't know how to access the Save Thumbnail feature programatically, but if you have a Excel file with a thumbnail and want to extract the image you could use the following code (using the OpenXml 2.0 API):
Private Sub ExtractThumbnailAsPng(ByVal pathToExcelFile As String, ByVal outputPath As String)
Dim thumbnailPart As DocumentFormat.OpenXml.Packaging.ThumbnailPart
Using excelFile As SpreadsheetDocument = SpreadsheetDocument.Open(pathToExcelFile, True)
thumbnailPart = excelFile.ThumbnailPart
If thumbnailPart IsNot Nothing Then
Using thumbnailStream As Stream = thumbnailPart.GetStream(FileMode.Open, FileAccess.ReadWrite)
Dim thumbBitmap As New Bitmap(thumbnailStream)
thumbBitmap.Save(outputPath, System.Drawing.Imaging.ImageFormat.Png)
End Using
End If
End Using
End Sub
Since this isn't Excel automation you could do this server side as well.
Related
How can I open the password-protected PowerPoint presentation using C# or VBA,in excel workbook.open the method has a password parameter. But in PowerPoint, it does not have.
In PowerPoint Presentation.Open method does not have a password parameter
In Excel, I can use
Application.Workbooks.Open(Filename,Password) But there is no equivalent in PowerPoint
I need to pass the password during PowerPoint document open
This will Work: Tested in VBA
Dim PVW As ProtectedViewWindow, Pres As Presentation
Set PVW = ProtectedViewWindows.Open("Full Path ", "Password")
Set Pres = PVW.Edit("modify")
Another Method: Untested
Sub SetPassword()
With Presentations.Open(FileName:="C:\My Documents\Earnings.ppt")
.Password = complexstrPWD 'global variable
.Save
.Close
End With
End Sub
Taken From: Link
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.
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
I am wondering how do I extract data out of a 2007 excel file? I am using asp.net mvc 3. My plan is to have a upload section that you choose a file and hit upload. I have no clue after that what kind of format it will be or what I need to do to extract the values out.
Thanks
Once you have the spreadsheet uploaded and you save it to a file on the web server it is quite easy to use LINQ to select the rows from the spreadsheet. Check this out for more info.
http://code.google.com/p/linqtoexcel/
The easiest way to read excel spread sheets IMO is to use a DataAdapter and an OleDB connection as shown in this code project sample. The good thing about this is it does not have any dependencies on COM or the MS office libraries.
For reading Excel files, I learned to love Koogra. It's an open source library that reads both xls and xlsx files, and is very easy to use.
http://sourceforge.net/projects/koogra/
I've used NPOI and it's quite simple to use:
Using Xlfile As FileStream = New FileStream(FileName, FileMode.Open, FileAccess.Read)
Using XLBook As HSSFWorkbook = New HSSFWorkbook(Xlfile)
Using XLSheet As NPOI.SS.UserModel.Sheet = XLBook.GetSheetAt(0)
Dim CurrentRow As NPOI.HSSF.UserModel.HSSFRow
Dim CurrentCell As NPOI.SS.UserModel.Cell
Dim RowEnum As IEnumerator = XLSheet.GetRowEnumerator()
While RowEnum.MoveNext
If (RowEnum.Current IsNot Nothing) Then
CurrentRow = TryCast(RowEnum.Current, NPOI.HSSF.UserModel.HSSFRow)
Select Case CurrentCell.CellType
Case NPOI.SS.UserModel.CellType.STRING
' CurrentCell.StringCellValue
Case NPOI.SS.UserModel.CellType.NUMERIC
' CurrentCell.NumericCellValue.ToString()
End Select
End While
End Using
End Using
Xlfile.Close()
End Using
I need to open a Microsoft Word 2003 file and change its file properties. Such as changing the Subject in the Summary Tab.
Microsoft provides a very useful little assembly called DSOFile. With a reference to it in your project, you can modify Office document properties. It won't necessarily let you open the actual Office file's properties dialog, but you could certainly simulate it.
According to Microsoft:
The Dsofile.dll files lets you edit
Office document properties when you do
not have Office installed
More details and a download link can be found at http://support.microsoft.com/kb/224351
Here's a snippet some (very old) VB code I used ages ago. Sorry I haven't converted to C# and be aware that it's part of a class so there are references to instance variables. Still, it should be pretty easy to understand and covert to your own needs:
Private Sub ProcessOfficeDocument(ByVal fileName As String)
Dim docDSO As New DSOFile.OleDocumentPropertiesClass
Dim docTitle, docModified, docAuthor, docKeywords As String
Try
docDSO.Open(fileName, True)
Dim docSummary As DSOFile.SummaryProperties = docDSO.SummaryProperties
docTitle = docSummary.Title
docAuthor = docSummary.Author
docKeywords = docSummary.Keywords
docModified = CStr(docSummary.DateLastSaved)
If (Not String.IsNullOrEmpty(docTitle)) Then
_Title = docTitle
End If
If (Not String.IsNullOrEmpty(docAuthor)) Then
_Author = docAuthor
End If
If (Not String.IsNullOrEmpty(docModified)) Then
_DateModified = DateTime.Parse(docModified)
End If
Catch ex As Exception
'Do whatever you need to do here...'
Finally
If (Not docDSO Is Nothing) Then
docDSO.Close()
End If
End Try
End Sub
I can think of 2 ways to do this:
Use the Microsoft Office APIs. You
will have to reference them in your
project, and you will need the
Primary Interop Assemblies.
Convert the file to the Word 2003
XML format and change that value in
the XML document. Here is the MSDN
documentation on the document
properties:
http://msdn.microsoft.com/en-us/library/aa223625(office.11).aspx
I would go with the second option if you can, because that way you don't have to depend on Word being installed on the system.