I want to edit the current active Excel-Worksheet in NPOI.
The Codesample below Shows what I want to do. Problem is I would need it in NPOI and so I am asking whether any of you can help me as I can't find anything.
Microsoft.Office.Interop.Excel.Application excel = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Microsoft.Office.Interop.Excel._Workbook wb = excel.ActiveWorkbook;
NPOI is not a wrapper around Office, it implements it's own access to the files. As such, it cannot be used to get the "Active" instance of Excel. It never directly interops with Excel in the first place. That's one of the features that makes it a powerful library, it doesn't depend on Office being installed and can therefore run on a server in an unattended way.
In case you want to interact directly with Excel, you need to use the Microsoft Primary Interop Assemblies, which will work just fine with the statements you referenced in your Question.
Related
I have had previous experience working with an Excel Add-In vsto COM object. Specifically using the Excel.Interop dll to create a worksheet and populate it with data. As well as, interact with the worksheet by using the worksheet change events to update data, thru c#. I wanted to explore Excel DNA and possibly use it. I am completely new to excel dna, but while researching it I only found examples of creating functions and a ribbon with buttons, but I haven't seen a way to create a worksheet and populate it from a datatable.
Is Excel DNA only used for the creation of the excel add in and if I wanted to create a worksheet, populate it with data and have events I either need to use excel.interop dll or OpenXML?
Excel-DNA is meant to allow you to run .NET code from within Excel. If you want, for example, to have a custom Ribbon in Excel, with a button that, when clicked, will run some .NET code to create a new Workbook and populate some data, etc. then yes... Excel-DNA is a great tool for that.
If you want to create Excel files outside of Excel, for example, in a Console App or Windows Service, then Excel-DNA is not the right tool for that, and you should look at using the Excel.Interop if you know your app will run on a machine with Excel installed, or other alternatives such as ClosedXml and other OpenXml-compatible tools, that will generate Excel files without requiring Excel installed on the machine.
You have full access to the Excel COM Object Model from within your Excel-DNA add-in. One important step is that you have to get hold of the correct Application root object for the Excel instance that is hosting your add-in. (Just calling new Application() might get hold of another Excel instance.) To get hold of the Application object you call ExcelDnaUtil.Application - that return the COM object.
From there you can use the dynamic support in C# to talk to the object model. But better is to reference the Interop assemblies, giving you IntelliSense and early-binding.
A convenient way of referencing a set of interop assemblies (corresponding to the Excel 2010 object model) is to install the ExcelDna.Interop package from NuGet. With the 'Embed Interop Types' feature in .NET 4 (which is set true by default), you need not redistribute anything special and your code will be compatible with all Excel versions, as long as the object model parts you use are supported there.
As an entry point into running the COM code, you can make a macro, shortcut ribbon or context menu. From the object model you could also hook COM events.
A simple example with detailed instructions for making a Ribbon button that then runs some COM code is available on GitHub.
Note that the VSTO wrappers on top of the COM object model (everything in a Microsoft.Office.Tools.Excel namespace) are not compatible with your Excel-DNA add-in, so you'd have to implement that functionality yourself based on the native COM object model (the types in the Microsoft.Office.Interop.Excel namespace.)
I am trying to use SpreadsheetGear to access an excel file that is downloaded and opened from a website. I haven't been able to find a way to set an already open and active excel file to a SpreadsheetGear workbook. Saving and then opening from memory is not an option in this circumstance.
I have been using this code to access the application before I started working with SpreadsheetGear:
xl.Application excelApp = (xl.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
However, none of the interfaces I've found for spreadsheetGear are compatible with that variable.
This is not possible with SpreadsheetGear for .NET, as it does not interact with Microsoft Excel in any way (it's a totally separate product, built from the ground up using only the .NET Framework and has no dependencies on Microsoft Excel).
To open a file in SpreadsheetGear, you'll need to use one of the following methods to do so...
SpreadsheetGear.Factory.GetWorbook(pathToFile)
SpreadsheetGear.IWorkbooks.Open(pathToFile) / OpenFromMemory(byteArray) / OpenFromStream(streamObj)
...which means you'll need to save the file from Excel first.
I have a windows form that works fine on my machine, I have a reference to the Microsoft.Interop Assembly for Excel 2007. Certain machines will have both Excel 2000 and Excel 2007 installed, and if Excel 2007 is not set as the "Default" version of Excel the windows form will throw an error and not work. Is their a way I can "package" my windows form to allow it to run error free on a machine with both 2000 and 2007 installed?
You're currently using Early Binding to access Excel. This is where you embed your reference to the interop in the project before compiling.
Advantages
Version of Excel is known to the compiler
Faster execution as we know that the methods exist and where they are
Allows us to use intellisense to check arguments are correct and that return types are correct
Disadvantages
Supports only the embedded versions of Excel
You need to take a look at Late Binding. This is where the interop is not included in the project at all and instead is bound later through reflection. You basically trade off all the advantages above for being able to support multiple versions of Excel.
There's lots of guides online that talk about how to do it.
How to use use late binding to get excel instance?
C# : Late Binding Excel Interop Tutorial
Word Automation using Late binding - Usage of dynamic Keyword
My two cents
I must echo Hans comment, this is a bad idea. Trying to support a 15 year old version of Excel is a recipe for massive headaches and I think you'll quickly look to avoid doing this.
Unless you're absolutely set on doing it this way, maybe you can look at a third party library like EPPlus. Or if you only need to read the sheet, do it some alternate way like ODBC and avoid this altogether.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I noticed while preparing to my business scale, I realized too long time was spent to this work. An excel file is sent to us from the council via Internet, we calculate our works and send them using same way. So I want to automate preparing business scale.
For this, I created a windows forms application. My application is a desktop application (WinForms). All datas are written into textboxes. When we click OK button, programme must read "template.xls" and replace all variables which shows brackets "{}" with textboxes values. But I don't know how reading .xls file, replacing variables with values and saving template as a finished document. I have added screenshot of excel file below.
Could you help me how can I do this?
Kind regards.
IF your application is a desktop application (WinForms, WPF) then you can use Interop. It requires Excel locally installed. BUT BEWARE: Interop is not supported in sever-scenarios by MS.
If Excel is not locally installed and/or this is something you want to do server-side (like ASP.NET or similar) there are many options to read/edit/create Excel files without Interop/installing Excel on the server:
MS provides the free OpenXML SDK V 2.0 - see http://msdn.microsoft.com/en-us/library/bb448854%28office.14%29.aspx (XLSX only)
This can read+write MS Office files (including Excel).
Another free option see http://www.codeproject.com/KB/office/OpenXML.aspx (XLSX only)
IF you need more like handling older Excel versions (like XLS, not only XLSX), rendering, creating PDFs, formulas etc. then there are different free and commercial libraries like ClosedXML (free, XLSX only), EPPlus (free, XLSX only), Aspose.Cells, SpreadsheetGear, LibXL and Flexcel etc.
EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx).
Usage examples can be found here and in the project site.
It is as simple as
ws.Cells["B1"].Value = "My Cell Value";
You can read from the excel file (the cells that have your bracket fields {*}), replace them as needed and save.
To check if the cell has a field you can use regular expression like Regex.IsMatch(cellValue, "\{.*\}")
Its seamless, since it uses the Open Office format, then you don't need Excel to be installed.
If you choose, on the other hand, to make this a web-base app or even a desktop PHP app, I can highly recommend the PHP Excel library, While producing spreadsheets takes quite a bit of time, reading the data from a sheet is a few simple lines of code and you're presented with an array that holds values of all the active cells. It can handle sheets with multiple pages and even formulaic data.
My company uses NPOI. Can be found here:
http://npoi.codeplex.com/
It does not require excel to be installed and can work with .net 2.0 and above. It's documentation is not complete, but you can search it's java equivalent (it has the same classes and methods) here:
http://poi.apache.org/
If you know that you'll have excel installed you can try using oledb
http://www.codeproject.com/Articles/8500/Reading-and-Writing-Excel-using-OLEDB
but I think it works only for xls not xlsx.
For reading xls document you can use this code. After
1.you can add all of value at string arraylist.
2. you can use regex. for example
if(a.include("{"))
replaceall("{","") like that.
I give you algorithm. Umarım yardımcı olmuştur dostum :)
// Get the file we are going to process
var existingFile = new FileInfo(filePath);
// Open and read the XlSX file.
using (var package = new ExcelPackage(existingFile))
{
// Get the work book in the file
ExcelWorkbook workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
// Get the first worksheet
ExcelWorksheet currentWorksheet = workBook.Worksheets.First();
// read some data
object col1Header = currentWorksheet.Cells[0, 1].Value;
Sorry to hear that, but you don't need to attack it using C#. VB Script would have been a better fit. But either way, I would have maintained a separate mapping (as in source fields and excel cell location) than filling the excel cells with tags. It's my pet peeve to preserve the original "template".
For this solution, I'll assume you'll run it on a PC with Excel installed.
First, add reference to library Microsoft.Office.Interop.Excel. Then, use its namespace:
using Excel = Microsoft.Office.Interop.Excel;
Be warned that because it's COM Interop, you need to retain each and every reference to objects from this library to properly release them from memory with Marshal. This is golden rule to use COM Interop objects from .NET projects. For more info, read it here: How do I properly clean up Excel interop objects?
So, this is another important import:
using System.Runtime.InteropServices;
I don't know how you're filling this form, but I'll suppose there is one field for each data between brackets: {CITY}, {NUM_I1}, and so on.
So, in your form submission, you could create a dictionary out of your inputs:
Dictionary<string, string> replacing = new Dictionary<string, string>();
replacing.Add("{CITY}",txtCity.Text);
...
And then, for filling the Workbook:
//Opening Excel Application with desirable template Workbook
//and instantiating the desirable Worksheet and Range
Excel.Application xlApplication = new Excel.Application();
Excel.Workbooks xlWorkbooks = xlApplication.Workbooks;
Excel.Workbook xlWorkbook = xlWorkbooks.Open(templateFilename, ReadOnly: true);
Excel.Sheets xlSheets = xlWorkbook.Sheets;
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlSheets[sheetNameOrIndex];
Excel.xlFirstCell = xlWorksheet.Cells[firstRow, firstCol];
Excel.xlLastCell = xlWorksheet.Cells[lastRow, lastCol];
Excel.Range xlRange = xlWorksheet.Cells[xlFirstCell, xlLastCell];
//all of the replacing
foreach (string key in replacing.Keys)
xlRange.Replace(key, replacing[key]);
//saving
xlWorkbook.SaveAs(newFilename);
//important part: releasing references
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlFirstCell);
Marshal.ReleaseComObject(xlLastCell);
Marshal.ReleaseComObject(xlWorksheet);
Marshal.ReleaseComObject(xlSheets);
xlWorkbook.Close(SaveChanges: false);
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlWorkbooks);
xlApplication.Exit();
Marshal.ReleaseComObject(xlApplication);
I've made it using c# 4.0. If you need it to develop it under Visual Studio 2008 or older, which don't support optional parameters, you just need to pass Type.Missing to parameters you don't want to use under Excel library methods (Workbooks.Open and Range.Replace).
Hi I am creating an application through which i need to create an excel. I have added Microsoft Excel 12.Object Library as Reference to application. But my server didnt get Msoffice Installed in it. So how can i create Excel in that server.
I can recommend EPPlus because it's simple, powerful and works without having office/excel being installed with Excel 2007 spreadsheets(xlsx-files). It's license model is LGPL.
var excel = new ExcelPackage();
excel.File = new System.IO.FileInfo(#"C:\Temp\AnExcelFile.xlsx");
if (excel.File.Exists)
excel.Load(excel.File.Open(FileMode.Open));
ExcelWorksheet ws = excel.Workbook.Worksheets.Add("Worksheet-Name");//must be unique and less than 31 characters long
ws.Cells[26, 1].LoadFromDataTable(dt, true); //loading from DataTable, the 2.Parameter is PrintHeaders
ws.Cells[26, 1].LoadFromCollection(query, true); //loading by LINQ-Query also possible
excel.Save();
If you need to create new office format documents known as openxml, you can see at http://www.microsoft.com/en-us/download/details.aspx?id=5124
There are a number of third party libraries - I think ComponentOne makes one, for instance - which are capable of creating Excel files, and I think at least some of them are independent of Excel, so they can make Excel files without having Excel installed on the server.
An alternate solution would be to create some other format that Excel can read, for instance CSV. Using CSV will mean that you don't get the fancy formatting provided by Excel, but at least you don't need to license a third party component or install Excel on the server.
There is now way to create ms objects, while MS Office is not installed.
Added library is nothing more than interfaces wrapper.