function xlcontrol(range,params,file,sheet)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Simple Styling of of excelsheets
%
% IN: range ex. 'A1:D5'
% params
% params.Bold; 1 or 0
% -integer, Must be 1 or 0, if 1 bold if 0 not bold
% params.FontName
% -character string, with valid font name, like 'Times'
% or 'Arial'
% params.FontSize
% -integer which controls fontsize
% params.ColorIndex
% -integer, Colorindex which sets textcolor min 0 max 56
% params.NumberFormat
% -integer, Selects numberformat of numbers
% params.Int_Colorindex
% -integer, select cellcolor min 0 max 56
% params.Border
% -integer, 1 or 0, 1= border;0=not border
% params.BorderWeight
% -integer, sets thickness of cellborder maxvalue 4
% minvalue 1 requires Border to be set to 1
% file ex 'c:\temp\test.xls'
% sheet ex 'January'
%
%Author Peter Lindberg
%Date: 091228
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Excel = actxserver('Excel.Application'); %start activex
ExcelWorkbook = Excel.workbooks.Open(file);
message = activate_sheet(Excel,sheet);
% Select range in worksheet.
Select(Range(Excel,sprintf('%s',range)))
A = get(Excel.selection,'Value');
%% Excel.selection.Font.Italic = 'True'
try
if isnumeric(params.Bold)
if params.Bold == 1
Excel.selection.Font.Bold = params.Bold;
else
Excel.selection.Font.Bold = 0;
end
else
disp('params.Bold must be numeric')
end
if ischar(params.FontName)
Excel.selection.Font.Name = params.FontName;
end
if params.FontSize ~= -1
Excel.selection.Font.Size = params.FontSize;
end
if params.ColorIndex ~= -1
Excel.selection.Font.ColorIndex = params.ColorIndex;
end
if params.NumberFormat ~= -1
Excel.selection.NumberFormat = params.NumberFormat;
end
if params.Int_ColorIndex ~= -1
Excel.selection.Interior.ColorIndex = params.Int_ColorIndex;
end
if params.Border == 1
Excel.Selection.Border.Item(4).Weight = params.BorderWeight;
Excel.Selection.Border.Item(1).Weight = params.BorderWeight;
Excel.Selection.Border.Item(2).Weight = params.BorderWeight;
Excel.Selection.Border.Item(3).Weight = params.BorderWeight;
end
catch ME
ExcelWorkbook.Save
ExcelWorkbook.Close(false)
delete(Excel)
disp(ME.message)
return
end
%%
ExcelWorkbook.Save; % saves workbook
ExcelWorkbook.Close(false); % Close Excel workbook.
delete(Excel); %really closes excelbook
%%
function message = activate_sheet(Excel,sheet)
% Subfunction that Activates specified worksheet in workbook.
% Or if sheet is nonexistant creates a new sheet
% Initialise worksheet object
WorkSheets = Excel.sheets;
message = struct('message',{''},'identifier',{''});
% Get name of specified worksheet from workbook
try
TargetSheet = get(WorkSheets,'item',sheet); % Check if sheet exists
catch
try
Sheet = invoke(WorkSheets,'Add') % if sheet does not exists, we create a new sheet
Sheet.name = sheet % named as the inarg sheet
TargetSheet = Sheet
catch ME
disp(ME.message)
disp('HI!')
delete(Excel)
return
end
end
% activate worksheet
Activate(TargetSheet)