function ExcelDemo
clc;
close all;
clear all;
fullFileName = GetXLFileName();
if isempty(fullFileName)
return;
end
Excel = actxserver('Excel.Application');
excelVersion = str2double(Excel.Version);
if excelVersion < 12
excelExtension = '.xls';
else
excelExtension = '.xlsx';
end
switch excelExtension
case '.xls'
xlFormat = -4143;
case '.xlsb'
xlFormat = 50;
case '.xlsx'
xlFormat = 51;
case '.xlsm'
xlFormat = 52;
otherwise
xlFormat = -4143;
end
if ~exist(fullFileName, 'file')
message = sprintf('I am going to create Excel workbook:\n\n%s\n\nClick OK to continue.\nClick Exit to exit this function', fullFileName);
button = questdlg(message, 'Creating new workbook', 'OK', 'Exit', 'OK');
drawnow;
if strcmpi(button, 'Exit')
return;
end
ExcelWorkbook = Excel.workbooks.Add;
ExcelWorkbook.SaveAs(fullFileName, xlFormat);
ExcelWorkbook.Close(false);
else
delete(fullFileName);
end
invoke(Excel.Workbooks,'Open', fullFileName);
Excel.visible = true;
myData = magic(20);
myOtherData = rand(10);
xlswrite1(fullFileName, myData, 'mySheetName', 'B2');
ca = {'Column Header 1', 'Column Header 2'};
xlswrite1(fullFileName, ca, 'mySheetName', 'B1');
ca = {'Row Header 1'; 'Row Header 2'};
xlswrite1(fullFileName, ca, 'mySheetName', 'A2');
xlswrite1(fullFileName, myOtherData, 'myOtherSheetName', 'B2');
DeleteEmptyExcelSheets(Excel);
worksheets = Excel.sheets;
thisSheet = get(worksheets, 'Item', 1);
for k = 1 : 12
myComment = sprintf('Comment for cell A%d', k);
cellReference = sprintf('A%d', k);
theCell = thisSheet.Range(cellReference);
theCell.AddComment(myComment);
end
invoke(Excel.ActiveWorkbook,'Save');
Excel.Quit;
Excel.delete;
clear Excel;
message = sprintf('Done!\nThis Excel workbook has been created:\n%s', fullFileName);
msgbox(message);
function fullExcelFileName = GetXLFileName()
fullExcelFileName = [];
FilterSpec = {'*.xls', 'Excel workbooks (*.xls)'; '*.*', 'All Files (*.*)'};
DialogTitle = 'Save workbook file name';
thisFile = mfilename('fullpath');
[thisFolder, baseFileName, ext] = fileparts(thisFile);
DefaultName = sprintf('%s/%s.xls', thisFolder, baseFileName);
[fileName, specifiedFolder] = uiputfile(FilterSpec, DialogTitle, DefaultName);
if fileName == 0
return;
end
[folder, baseFileName, ext] = fileparts(fileName);
fullExcelFileName = fullfile(specifiedFolder, [baseFileName '.xls']);
function DeleteEmptyExcelSheets(excelObject)
worksheets = excelObject.sheets;
sheetIdx = 1;
sheetIdx2 = 1;
numSheets = worksheets.Count;
excelObject.EnableSound = false;
while sheetIdx2 <= numSheets
temp = worksheets.count;
if or(sheetIdx>1,numSheets-sheetIdx2>0)
if worksheets.Item(sheetIdx).UsedRange.Count == 1
worksheets.Item(sheetIdx).Delete;
end
end
if temp == worksheets.count;
sheetIdx = sheetIdx + 1;
end
sheetIdx2 = sheetIdx2 + 1;
end
excelObject.EnableSound = true;
return;
Best Answer