简体   繁体   中英

Excel Interop “New Up” objects

I'm working on an MVC application where users can upload an excel document and output HTML but I'm having some difficulty with the Interop libraries and I hope someone can help.

To keep this really simple, I have reached a stage where I want to instantiate or "new up" a worksheet and use the id of the chosen sheet. The user has selected the sheet they wish to use but there doesn't seem to be any method of doing this.

I have tried code such as workbookModel.workbook.Sheets.get_Item(1); which should get the current workbook in the model and get the sheet with id 1 - I believe this is 1 based index as opposed to 0-based. Bear in mind I have some viewModels in play hence above code, but all I'm really doing here is Workbook work = new Workbook().Sheets.get_Item(1);

I have also tried Workbook work = new Workbook().Worksheets.get_Item(1); in case I was incorrectly using Worksheets instead of sheets but I don't believe so.

But nothing I've tried seems to work.

If anyone can point me in the right direction that will be much appreciated and if this hasn't made sense and you need more info please let me know.

Thanks a lot

First of all, Interop only works if you have an excel application running.

So, if you don't have it running, you will need to:

Application ExcelApp = new Application();

To get a worksheet from the application, you will need the workbook first. You can get the workbook with one of the following:

//to get the first workbook of an application
Workbook MyBook = ExcelApp.Workbooks[1];

//to get a workbook by name
Workbook MyBook = ExcelApp.Workbooks["bookname"];

//to open a workbook from a xls file
Workbook MyBook = ExcelApp.Workbooks.Open(name and other parameters);

//to add a new workbook to the application
Workbook MyBook = ExcelApp.Workbooks.Add(optional template);

Note that a workbook cannot exist without the running application, nor a sheet can exist without a parent workbook in a running application

To get a worksheet from a workbook, you will need to cast it, because it comes as object .

//to get an existing sheet
Worksheet MySheet = (Worksheet)MyBook.Worksheets["sheetname"];

//to create a new sheet
Worksheet MySheet = (Worksheet)MyBook.Worksheets.Add(some parameters);

But if you could manage to get the names from the sheets to populate the view with links, you could store those sheet instances and pass them to the method that creates the html. Or store them in global variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM