Documentation Center

  • Trial Software
  • Product Updates

Work with Microsoft Excel Spreadsheets Using .NET

This example creates a spreadsheet, copies some MATLAB® data to it, and closes it. The example uses classes from the Microsoft.Office.Interop.Excel.ApplicationClass class. For information about the class and using the interface with different versions of Excel®, refer to documentation on the MSDN® Web site http://msdn.microsoft.com/.

To create a workbook, type:

NET.addAssembly('microsoft.office.interop.excel');
app = Microsoft.Office.Interop.Excel.ApplicationClass;
books = app.Workbooks;
newWB = Add(books);
app.Visible = true;

Create a new sheet:

sheets = newWB.Worksheets;
newSheet = Item(sheets,1);

newSheet is a System.__ComObject because sheets.Item can return different types, such as a Chart or a Worksheet. To make the sheet a Worksheet, use the command:

newWS = Microsoft.Office.Interop.Excel.Worksheet(newSheet);

Create MATLAB data and write it to a range of cells:

excelArray = rand(10);
newRange = Range(newWS,'A1');
newRange.Value2 = 'Data from Location A';
newRange = Range(newWS,'A3:B12');
newRange.Value2 = excelArray;

Modify cell format and name the worksheet:

newFont =  newRange.Font;
newFont.Bold = 1;
newWS.Name = 'Test Data';

If this is a new spreadsheet, use the SaveAs method:

SaveAs(newWB,'mySpreadsheet.xlsx');

Close and quit:

Close(newWB);
Quit(app);
Was this topic helpful?