This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the 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

To create a workbook, type:

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:


Close and quit:


Related Examples

External Websites

Was this topic helpful?