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
Related
I am using the Syncfusion.XlsIO.WinForms dependency to develop with C# but when generating a file a sheet is generated that says "Created with a trial version of Syncfusion Essential XlsIO" so I think it is paid. I have been looking for a free NuGet package to modify an excel file however many dependencies remove objects like macros and textboxes on save with a function like SaveAs or Save (Macros and textboxes are part of the document). excel and I don't generate them by code, they belong to the file). I have been using a free option like ClosedXML but it deletes the elements, I have been using this code:
XLWorkbook workbook = XLWorkbook.OpenFromTemplate("C://template//from123.xlsx");
var hoja = workbook.Worksheets.Worksheet(1).Worksheet;
hoja.Cell("B11").Value = "5";
//hoja.Cell("CN").Style.Fill.SetBackgroundColor(XLColor.Black);
workbook.SaveAs(#"C://template" + "//" + "XMLCopy" + ".xlsx");
The result is as follows:
Before modifying the file
After modifying the file with c# and closedXml and saving
Do you know how I can make a modification for free and without deleting my elements?
You should open the original excel file by creating a new workbook object, modify it and then save it as a new file:
using (XLWorkbook workbook = new XLWorkbook("C://template//from123.xlsx"))
{
var hoja = workbook.Worksheets.Worksheet(1);
hoja.Cell("B11").Value = "5";
//hoja.Cell("CN").Style.Fill.SetBackgroundColor(XLColor.Black);
workbook.SaveAs(#"C://template" + "//" + "XMLCopy" + ".xlsx");
}
Is it possible to set the excel filename before file saving?
I have following simple code:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook workbook = excel.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet sheet = workbook.Sheets[1];
sheet.Cells[1, 1] = "Hello World!";
Is it possible to predefine this name before saving?
Thanks.
There is no explicit, foolproof way to do this prior to saving, unfortunately. The closest you could come is to use a template. If you have a template called FOO.xltx, you could create your workbook like this:
Application.Workbooks.Add "X:\path\to\FOO.xltx"
The only quirk is that the name for the new documents will be appended with an incrementing number (FOO1 the first time, then FOO2,FOO3, etc.).
To create a template, just create a new document, and when you save it, select Excel Template (*.xltx) from the Save as type dropdown.
You have to use saveas to save the file with the filename you want. Then when the user clicks save it will just update the file that was previously created. Unfortunately there is no other way. Here is the code:
workbook.SaveAs(Filename: FILENAMEHERE);
Here is the MSDN doc for it: https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas.aspx
at the moment my current process is as followed. Query database - > Save file locally -> Open Workbook using Excel Interop Dll, Make Changes To Work Book, Save As using Excel Interop Dll. The reason for save as is because I require some addition settings so the file isn't set to read only.
The issue I'm coming across is that it's saving locally twice. First time is fine, second time a prompt will appear asking if I would like to override. I'm wondering how can I remove the Save File Locally process and have it in memory to work with? If I am able to work with the file in memory, I would have the prompt on Save As asking me if I would like to override the previous file.
Code:
//Save File Locally
System.IO.File.WriteAllBytes(saveFileDialog.FileName, Report.FileArray);
var fileLocation = saveFileDialog.InitialDirectory + saveFileDialog.FileName;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
// Open Workbook Using Excel Interop Dll
Workbook wb = excel.Workbooks.Open(fileLocation);
Worksheet ws1 = wb.Worksheets.get_Item("English");
//Make Changes To WorkBook
ws1.Range["E5"].Value = StartDate;
ws1.Range["G5"].Value = EndDate;
// Save AS Using Excel Interop With shared settings to remove read only access
wb.SaveAs(fileLocation, AccessMode: XlSaveAsAccessMode.xlShared);
Process.Start(fileLocation);
You'd better disable the prompt, to what I remember this is possible but it imply a lot of umnaged code...
Try this
Microsoft.Office.Interop.MSProject.Application msProjectApp = new Microsoft.Office.Interop.MSProject.Application();
msProjectApp.DisplayAlerts = false;
Edit
Microsoft.Office.Interop.Excel.Application msProjectApp = new Microsoft.Office.Interop.Excel.Application();
msProjectApp.Visible = true; //show the application and not need to start a process
msProjectApp.DisplayAlerts = false;
//Save File Locally
System.IO.File.WriteAllBytes(saveFileDialog.FileName, Report.FileArray);
var fileLocation = saveFileDialog.InitialDirectory + saveFileDialog.FileName;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
// Open Workbook Using Excel Interop Dll
Workbook wb = excel.Workbooks.Open(fileLocation);
Worksheet ws1 = wb.Worksheets.get_Item("English");
//Make Changes To WorkBook
ws1.Range["E5"].Value = StartDate;
ws1.Range["G5"].Value = EndDate;
// Save Only
wb.Save();
Remove Process.Start
excel.Visible = true;
excel.DisplayAlerts = false;
If you "own" the workbook and can set it up beforehand to play nice and are only loading in data, I find the OleDB Access SQL connection approach to be a better way to load raw data into SQL.
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.
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