MatrixBerryCore
ExcelFileUtils.m
Go to the documentation of this file.
1 classdef ExcelFileUtils
2  methods (Static)
3  function [isPos,activeXObj]=isExcelInstalled()
4  try
5  activeXObj = matlab.io.internal.getExcelInstance;
6  isPos=true;
7  catch
8  isPos=false;
9  activeXObj=[];
10  end
11  end
12  [success,theMessage,fileName]=xlsOrCsvWrite(fileName,dataMat,...
13  varargin)
14  end
15 
16 end
17 
18 function [isSuccess,SStatus,fileName]=xlsOrCsvWrite(fileName,dataMat,varargin)
19 import mxberry.core.throwerror;
20 import mxberry.log.log4j.Log4jConfigurator;
21 logger=Log4jConfigurator.getLogger();
22 %
23 N_MAX_XLS_ROWS=65536;
24 N_MAX_XLS_COLS=256;
25 %
26 [~,~,fileExt]=fileparts(fileName);
27 isXLSX=strcmpi(fileExt,'.xlsx');
28 %
29 isDataEmpty=isempty(dataMat);
30 
31 isTooManyRows=~isXLSX&&(size(dataMat,1)>N_MAX_XLS_ROWS);
32 isTooManyCols=~isXLSX&&(size(dataMat,2)>N_MAX_XLS_COLS);
33 %
34 if isDataEmpty||isTooManyRows||isTooManyCols
35  isWriteCSV=true;
36  if isDataEmpty
37  warnStr='data is empty';
38  elseif isTooManyRows
39  warnStr='too many rows';
40  else
41  warnStr='too many columns';
42  end
43  logger.warn(sprintf(['Result will be written to ',...
44  'csv file, reason: %s'],warnStr));
45 else
46  isExcelInstalled=mxberry.io.xls.ExcelFileUtils.isExcelInstalled();
47  if ~isExcelInstalled
48  logger.warn(['Cannot get access to Excel ActiveX ',...
49  'server, using CSV format']);
50  % write data as CSV file, that is, comma delimited.
51  isWriteCSV=true;
52  else
53  isWriteCSV=false;
54  end
55 end
56 %
57 if isWriteCSV
58  fileName = regexprep(fileName,'(\.xls[^.]*+)$','.csv');
59  try
60  mxberry.core.cell.csvwrite(fileName,dataMat);
61  isSuccess = true;
62  SStatus.message='';
63  SStatus.identifier='';
64  %
65  catch exception
66  exceptionNew = throwerror('cantExportData',...
67  'An error occurred on data export in CSV format.');
68  exceptionNew = exceptionNew.addCause(exception);
69  if nargout == 0
70  % Throw error.
71  throw(exceptionNew);
72  else
73  isSuccess = false;
74  SStatus.message = exceptionNew.getReport;
75  SStatus.identifier = exceptionNew.identifier;
76  SStatus.exceptionObject=exceptionNew;
77  end
78  end
79 else
80  [isSuccess,SStatus]=xlswrite(fileName,dataMat,varargin{:});
81 end
function throwerror(in msgTag, in varargin)
THROWERROR works similarly to built-in ERROR function in case when there is no output arguments but s...
function csvwrite(in fileName, in inpCMat, in varargin)
CSVWRITE writes a specified cell matrix into a comma-separated file specified by name. All columns of the matrix are expected to be of the same type. As of the moment only 'char' and all numeric types are supported.