Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

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® website 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 columns 1 and 2 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;

Add three text strings to column C.

% Create a 3x1 System.Object
strArray = NET.createArray('System.Object',3,1);
strArray(1,1) = 'Add';
strArray(2,1) = 'text';
strArray(3,1) = 'to column C';
newRange = Range(newWS,'C3:C5');
newRange.Value2 = strArray;

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)

Related Examples

External Websites

Was this topic helpful?