Code covered by the BSD License  

Highlights from
xlwrite: Generate XLS(X) files without Excel on Mac/Linux/Win

4.8 | 45 ratings Rate this file 213 Downloads (last 30 days) File Size: 8.45 MB File ID: #38591 Version: 1.9
image thumbnail

xlwrite: Generate XLS(X) files without Excel on Mac/Linux/Win



12 Oct 2012 (Updated )

Generates ‘.xls’ & '.xlsx' files on Mac/Linux/Win without Excel, using same syntax as xlswrite.

| Watch this File

File Information

xlwrite allows to generate '.xls' & '.xlsx' files easily without having Excel installed or using COM-objects. It generates Excel files by using the Apache POI java library. This way Excel files can be generated on any platform supporting Java, including Linux & mac.

xlwrite uses the same syntax as xlswrite, making it easy to integrate in current applications.

xlwrite supports following datatypes:
- string
- numerical
- logical/boolean
The type of data is kept in Excel: for example boolean data in matlab will be saved as boolean in Excel.

xlwrite also supports a combination of above datatypes in a cell array like for example:
xlsData = {1 true 'text' false; 10 -12.5 6 false};

To generate the Excel file without too much overhead, xlwrite interacts directly with the Apache POI library.

The original idea of this script is based on the xlwrite function written by Marin Deresco, however due to some limitations we had to write an improved version.

Although created under Matlab 2012a, xlwrite should also work for earlier versions of Matlab.

UPDATE: if you find any bugs, please contact me directly.


Xlwrite : Export Data To Excel From Matlab On Mac/Win inspired this file.

This file inspired Csvexport(Filename,Cell Vals), Csvimport(Filename), and Xl Range, Number2letter.

Required Products MATLAB
MATLAB release MATLAB 7.14 (R2012a)
Other requirements Requires Apache POI library. Binaries included in zip file.
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (111)
08 Feb 2016 Seb Biass

This is great! Is there a way to directly write Matlab tables (e.g. writetable function?). Thanks!

02 Feb 2016 Richard Crozier

I'm using xlwrite with Matlab 2015a, and the old poi 3.8 library. I was getting an error:

Undefined function or variable 'HSSFWorkbook'.

I was able to make this go away by modifying xlwrite.m to call the HSSFWorkbook function with the full path like so:


instead of relying on the import statements. Not sure why this solves the problem, maybe there's been a change in how import works.

Comment only
04 Dec 2015 Beatrix

Jan Buytaert, I am having the same issues, where the POI files are not being loaded. What was the issue that you found with poi-ooxml-3.12-20150511.jar ?

Comment only
20 Oct 2015 Jan Buytaert

But because of poi-ooxml-3.12-20150511.jar
it seems no longer possible to write XSLX. Writing XLS still works fine.

Strangely enough poi-oxml-3.8-20120326.jar writes XLSX without a problem.

Comment only
12 Oct 2015 Jan Buytaert

By the way: I use R2015b and found that the culprit file is: poi-ooxml-3.12-20150511.jar
The other POI 3.12 files are not to blame.

Comment only
06 Oct 2015 Jeffrey Girard

This was a great help, thank you.

05 Oct 2015 Dinesh Jayaraman  
04 Oct 2015 Miles

Miles (view profile)

I am successfully able to use this code to write the contents of a cell array into a specified cell of an .xlsx file in Excel 2011 for Mac, but how do I get the contents of the cell to keep the previous formatting of the cell? For example, the blank cell I am writing into is set to bold Cambria font size 10, but when I run this code, the contents of the cell change to non-bold Calibri (Body) font size 12. Is there a trick to keep the formatting the same? Thanks for the help!

Comment only
11 Aug 2015 Dan

Dan (view profile)

Well.... with regard to the "xlwrite creates xlsx files that cannot be read by xlsread on a mac" problem: Things have gotten better (2015a) in that an error is no longer generated HOWEVER only one value is read.

After running the 4 lines below:
sWorksheet='Worksheet Name';
xlwrite(sFile,{'Cell 1','Cell 2';'Cell 3','Cell 4'},sWorksheet);
[fu fu caDataRead]=xlsread(sFile, sWorksheet);

caDataRead only has the contents of one cell:
caDataRead = 'Cell 1'

Comment only
22 Jul 2015 Matthew Lawrence

I figured it out - it was because I didn't have the full filename (including extension). Once I had the extension added it works fine.

Comment only
21 Jul 2015 Matthew Lawrence

When I try to write a second worksheet, it just overwrites the first. When I try this:

testheader={'A' 'B' 'C'};
xlwrite('testfilename',testheader,'sheet 1')
xlwrite('testfilename',testheader,'sheet 2')

I just get a single worksheet with the header text. Am I doing something wrong?

Comment only
19 Jul 2015 Marshall

Marshall (view profile)

Add the following code to the beginning of xlwrite.m, and keep the poi_library folder in the same directory as xlwrite.m (i.e. if xlwrite.m is in /toolbox, then we have /toolbox/xlwrite.m and /toolbox/poi_library/...

% Check if POI lib is loaded
if exist('', 'class') ~= 8 ...
|| exist('org.apache.poi.hssf.usermodel.HSSFWorkbook', 'class') ~= 8 ...
|| exist('org.apache.poi.xssf.usermodel.XSSFWorkbook', 'class') ~= 8

% load into path



% make sure it worked
if(exist('', 'class') ~= 8 ...
|| exist('org.apache.poi.hssf.usermodel.HSSFWorkbook', 'class') ~= 8 ...
|| exist('org.apache.poi.xssf.usermodel.XSSFWorkbook', 'class') ~= 8)
'The POI library is not loaded in Matlab.\nCheck that POI jar files are in Matlab Java path!');

Comment only
16 Jul 2015 James Russell

My remarks below apply to another version of xlwrite at:

The present version works fine, once you figure out how to deal with the Java path, which is neither documented nor obvious.

I put the POI library in a subdirectory of a directory I use during startup, then moved the javaaddpath commands from Test_xlWrite to my startup.m and edited them to point to where I put the POI library, referencing it relative to where I execute the javaaddpath commands during startup.

The javaaddpath commands populate a "dynamic" Java path, and aren't meant for persistent use, but I have not been able to add to the 'static' Java path, I expect because of syntax of path designation. I'll appreciate clear instructions on populating the static path, but for now the dynamic path works.

The maintenance in File Exchange of two programs named xlwrite, with two series of updates to them, is very confusing - I'm surprised this is possible.

Comment only
15 Jul 2015 James Russell

I can't get this to go. It errors on "Undefined function or variable 'XSSWorkbook' (line 148). By that point it has already satisfied itself that it has what it needs in the way of poi library. But, perhaps it's checks are invalid. XSSWorkbook is some kind of template or structure from poi. Possibly a path to poi library issue?

Comment only
19 Jun 2015 Simon Henin

Simon Henin (view profile)

Worked perfectly.
OSX 10.10.3, MATLAB 2014a

10 Jun 2015 Alec de Zegher

@Lil shen: To export multiple variables in one sheet: Combine all the variables in one variabele, and use this variable in your xlwrite command.
Do you have the problem when you define a name for the sheet?

Comment only
10 Jun 2015 Lil shen

@Alec(08 Feb 2015): Hi Alec, it seems to me that calling the xlwrite command twice doesn't work, the latter sheet will overwrite the first sheet. And how can I export multiple variables in one sheet?

Comment only
01 Apr 2015 Pascal

Pascal (view profile)

Excellent function.

But I had to add one line just at the end of xlwrite in order to force excel to actualize formulas in cells when the created file is opened :

% Force the recalculation

% Write & close the workbook
fileOut =;

status = 1;

20 Feb 2015 Filipe

Filipe (view profile)

OK I found what was missing.

It seems that I needed a pair of curly brackets around the string:

It works now!

Comment only
20 Feb 2015 Filipe

Filipe (view profile)

Works great!

@Alex: I used J's (03 Dec 2014) suggestion and it worked out of the box. Please consider it!

Edit: I'm getting the string strain='Ecoli' spread through the cells from C10 to C14 when using

Why is that?

08 Feb 2015 Alec de Zegher

@Alexandra: this should work normally. Just call the xlwrite command twice:

Comment only
06 Feb 2015 alexandra kaufhold

Is there a way to use this function to create 2 sheets in one Excel file? I want to put some data on sheet 1 and some data on sheet 2, but I want it all in the same file

Comment only
16 Jan 2015 Anton Kaplun

Great Work. Thanks a lot!

03 Dec 2014 J

J (view profile)

Nearly perfect - I would suggest a autoloading of the needed libraries like this:

% Check if POI lib is loaded - try to autoload
if exist('', 'class') ~= 8 ...
|| exist('org.apache.poi.hssf.usermodel.HSSFWorkbook', 'class') ~= 8 ...
|| exist('org.apache.poi.xssf.usermodel.XSSFWorkbook', 'class') ~= 8
javaaddpath([cpath filesep 'poi_library' filesep 'poi-3.8-20120326.jar']);
javaaddpath([cpath filesep 'poi_library' filesep 'poi-ooxml-3.8-20120326.jar']);
javaaddpath([cpath filesep 'poi_library' filesep 'poi-ooxml-schemas-3.8-20120326.jar']);
javaaddpath([cpath filesep 'poi_library' filesep 'xmlbeans-2.3.0.jar']);
javaaddpath([cpath filesep 'poi_library' filesep 'dom4j-1.6.1.jar']);
'The POI library is not loaded in Matlab.\nAutoloading failed ...\nCheck that POI jar files are in Matlab Java path!');


That maintains a high flexibility and increases the flawless usability also for matlab beginners ...

kind regards,

24 Nov 2014 Metcalfe Lab

Hi Alex,

I'm having the same error some others were having, namely: "The POI library is not loaded in Matlab.
Check that POI jar files are in Matlab Java path!"

I've already added the whole xlwrite folder (with the poi_library folder) into the working directory, and also added a copy into the dynamic java path of MATLAB:

e.g. javaclasspath shows

Any suggestions?


Comment only
06 Nov 2014 Ben Petschel

Ben Petschel (view profile)

Ok the problem seems to be two of the tokens appear in reverse order to what getSheetNames was expecting. A fix that worked for me was to insert the following code before line 21 of toolbox/matlab/iofun/private/getSheetNames.m:

if isempty(match)
match = regexp(workbook_xml, ...
['<sheet name=".*(?<=<sheet name=")(?<sheetName>.+?)(?=" r:id="rId' num2str(sheetIDs(i)) '" sheetId=".*"/>)'], ...
'names' );

Comment only
14 Oct 2014 Martin

Martin (view profile)

Hi Alec
Thanks for solving most of my problem, I'm just left with one issue. How do I either delete the content of a Cell or overwrite it with Not a number =NA().
Currently trying =NA() I get a string instead of having excel evaluating it to "#N/A" which is not plotted rather than the string being plotted as 0.
Thanks Martin

Comment only
05 Oct 2014 Alec de Zegher

If you want to place the POI files somewhere else, it is possible, as long as you change the paths correctly in the "javaaddpath" commands.

Comment only
03 Sep 2014 Nikos

Nikos (view profile)

Hello again,
Problem solved, I had multiple copies of Text.xlWrite.m in different folders.
xlwrite works perfectly as long as Text.xlWrite.m and the folder poi_library are both in the current directory.
Sorry for the bother.
Thanks again, excellent work!

03 Sep 2014 Nikos

Nikos (view profile)

Hi Alec,
This project was much needed, thanks.
I seem to have the same proble as @azizulh khan and @Shawn - I get the error:
"The POI library is not loaded in Matlab.
Check that POI jar files are in Matlab Java path!"
I am certain poi_library is in my workspace and in the matlab path as is Text.xlWrite.m
Please help!
Kind regards, Nikos

Comment only
04 Aug 2014 Alec de Zegher

@Azizullah Khan
These should be in the zip file. Just extract the whole zip folder to your matlab workspace to make the demo work.

Comment only
01 Aug 2014 azizullah khan

sir,make me clear about poi library
how can i insert it and from where can i get these files.The jar files?

03 Jul 2014 Dan

Dan (view profile)

Nice job but I believe there is a small problem.
xlwrite is able to create an xlsx file with multiple worksheets which I can open with Excel but I cannot read this file with xlsread. However, if I open the xlsx file with excel and then simply hit save (ostensibly making no changes), I can then open with xlsread.

Any ideas?



Comment only
03 Jul 2014 Zhan Xiong  
21 Jun 2014 Gabriel

@Gaurav and others facing that bug,

This may be due to some unexpected formatting in some description xml file(s) in the xlsx.

If you have write access to the matlab installation, you can fix it by editing the file

replace line 12 with:
'<Relationship Id="rId(\d+?)" Type="" Target="worksheets/.*\.xml"\s*/>', ...

and line 19 with:
['<sheet name=".*(?<=<sheet name=")(?<sheetName>.+?)(?=" sheetId=".*" r:id="rId' num2str(sheetIDs(i)) '"\s*/>)'], ...

I have not tested this fix extensively but I think it should not cause problems with other files.

Sorry for hijacking your comment section, but this is the number one page on google at the moment for that issue.

Comment only
18 Jun 2014 Alec de Zegher


It seems like a bug in Matlab itself.
Best would to file a bug submission at the Mathworks.

If it is urgent, you can edit the xlsread.m file directly to remove the bug. I don't have 2014a, so I cannot correct it myself.


Comment only
18 Jun 2014 Gaurav

Gaurav (view profile)

The thing is, I'm writing hundreds of files so I can't open each one in openoffice and hit save to be able to read them with xlsread. Any work around will be appreciated.

Comment only
18 Jun 2014 Gaurav

Gaurav (view profile)

Great work, great help, thanks a lot mate!

I'm still having trouble reading the file created by xlwrite through xlsread. I have installed the latest version of of Matlab (2014a). The error I get is:

Error using xlsread (line 247)
No right hand side value for assignment.

But if I open the file in openoffice, hit delete on an empty cell (so not really changing anything), and save it then xlsread can read it. So, I guess they have not really fixed the bug with xlsread.

10 Jun 2014 D.

D. (view profile)

05 Jun 2014 Alec de Zegher

It seems the "poi_library" folder is not in the same folder as your Text.xlWrite.m file....

Comment only
05 Jun 2014 Alec de Zegher

@Volker Schardt
Sorry for the late reply. I will be more than happy to add your code to the zip file. Can you please contact me by Private Message?


Comment only
05 Jun 2014 Shaun

Shaun (view profile)

Hi Alec,
Thank you for your great work!
But I have a problem...
I'm using Mac OS X. Matlab 2013a.
i got the following error when run the Text_xlWrite.m.

Error using xlwrite (line 93)
The POI library is not loaded in Matlab.
Check that POI jar files are in Matlab Java path!

Files were loaded with no errors.
I downloaded following jar files.

I've run following codes.


I got errors when the following code was run.

xlwrite(fileName, xlsData, sheetName, startRange);

Comment only
05 Jun 2014 Shaun

Shaun (view profile)

29 May 2014 Brian

Brian (view profile)

12 May 2014 Volker Schardt

Nice work indeed!
@ thomas, based on Alec work I did an xlread function. But I haven't done all the cross check work for my input that are needed to provide a out of the box function which can be used by anyone. Maybe I can do this later this week.

@ Alec if you like I would offer you my code to inculde it to your package, instead of opening a new site here on file exchange

Comment only
12 May 2014 Volker Schardt  
11 May 2014 Stephan

@Alec. The function works writing xls-files, but importing the data again (by xlsread) leaves empty data and txt variables.

08 May 2014 Martin

Martin (view profile)

01 May 2014 Chris

Chris (view profile)

15 Apr 2014 thomas

thomas (view profile)

Hey, just a beautiful and useful function !
the only thing i changed is the auto-cast to cell array for dataset type (will do the same for tables)

if isa(A,'dataset')
A = dataset2cell(A);

Only one request : will you provide an xlread which does the same job in the other way ?


I also add the auto-import command :

pkg = dir(fullfile(fileparts(mfilename('fullpath')),'lib','*.jar'));
for i=1:length(pkg)
jar{i} = fullfile(fileparts(mfilename('fullpath')),'lib',pkg(i).name);

05 Apr 2014 florian

I am getting the following error when trying to paste a 28900,14 cell array in an xlsx file. it seems my memory funs out?

Warning: A Java exception occurred trying to load the sprintf class:
Java exception occurred:
java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.util.Arrays.copyOf(
at java.util.jar.JarFile.getEntry(
at java.util.jar.JarFile.getJarEntry(
at sun.misc.URLClassPath$JarLoader.getResource(
at sun.misc.URLClassPath.getResource(
at Method)
at java.lang.ClassLoader.loadClass(
at sun.misc.Launcher$AppClassLoader.loadClass(
at java.lang.ClassLoader.loadClass(
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(
at com.mathworks.util.jarloader.SimpleClassLoader.loadClass(
at com.mathworks.util.jarloader.SimpleClassLoader.loadClass(
at com.mathworks.jmi.OpaqueJavaInterface.findClass(
> In ExternalException>ExternalException.ExternalException at 35
In JavaException>JavaException.JavaException at 38
In xlwrite at 260
In dikablis_analysis at 445
Error using xlwrite (line 260)
Java exception occurred:
java.lang.OutOfMemoryError: GC overhead limit exceeded
at org.apache.poi.xssf.usermodel.XSSFRow.createCell(
at org.apache.poi.xssf.usermodel.XSSFRow.createCell(
at org.apache.poi.xssf.usermodel.XSSFRow.createCell(

Error in dikablis_analysis (line 445)

Comment only
05 Apr 2014 florian

feature request: table support...unfortunately it seems I can only export cells, vectors or matrixes but not tables?

Comment only
30 Jan 2014 Alec de Zegher

@Dan: I just got a reply back from Mathworks support:
"This bug should be fixed with R2014a. The PreRelease for R2014a is available already and it should also contain the bug fix."

Comment only
29 Jan 2014 Alec de Zegher

@Dan: XLSREAD has a bug in its implementation to read xlsx files; I have informed Mathworks support regarding this. The Mathworks development team has acknowlodged the bug. Don't know yet if they fixed it.

The workaround is to use xls files if you can.

Comment only
29 Jan 2014 Alec de Zegher

@Nik: can you send me a demo code so I can reproduce it and fix the bug?


Comment only
27 Jan 2014 Samuel

Samuel (view profile)

@Niklas: Try to specify the extension. For me the problem occured when not specifying it:

fileName = 'myfile' does not work with several sheets.

fileName = 'myfile.xlsx' does.

Don't ask me why.

Comment only
30 Dec 2013 Dan

Dan (view profile)

A great submission but there seems to be problems when I use xlsread to read these files. I am unable to read an xlsx workbook with multiple worksheets created with xlwrite (on a Mac). I just get "Worksheet not found".

Comment only
09 Dec 2013 Niklas Brown

Hi Alec,
am trying to write a multiple sheet .xls-File. Unfortunately, on every loop is overwrites the worksheet. So at the end I get an xls-File with one worksheet created in the last loop. Sheetname changes on every loop.
If I understand the description correctly, the function should add the worksheet a the end?!
Thanks for help!

Comment only
04 Dec 2013 Alessio Nava  
01 Dec 2013 SCADA Miner

Regarding the problem below. There was a corrupted existing myfile.xlsx already in the directory where xlwrite was trying to create the new file.

Comment only
01 Dec 2013 SCADA Miner

Hi Alec. I have been using this on Windows and it is great. I have moved m code onto a linux machine and am encountering the following exception:
java.lang.illegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream at ...WorkbookFactory.create( (line 137 or xlwrite: xlsWorkbook = WorkbookFactory.create(fileIn))
I am trying to create an xlsx file which has been working flawlessly in windows. i have checked all the .jar dependencies and they are identical on my windows install as the linux one. Any suggestions to help fault-finding?

19 Nov 2013 Alec de Zegher

Hello Guillaume,
Your are right. I will try to send a bug fix as soon as possible.

Best regards,

Comment only
15 Nov 2013 Guillaume

Oups my last post has been deleted.

Actually, i've got the following error

Error using xlwrite (line 179)
Java exception occurred:
java.lang.IllegalArgumentException: The workbook already contains a sheet of this name
at org.apache.poi.xssf.usermodel.XSSFWorkbook.createSheet(
at org.apache.poi.xssf.usermodel.XSSFWorkbook.createSheet(

when i used xlwrite several times on a new workbook with a specific worksheet (e.g. 8th sheet). The function created the workbook with one sheet named "sheet 8". So when i tried to use xlwrite again on the 8th sheet, xlwrite didn't recognized "sheet 8" as the 8th spreadsheet and tried to create a newer with the name "sheet 8". This induced the above error.

Comment only
15 Nov 2013 Guillaume

replacing line 179 : "xlsSheet = xlsWorkbook.createSheet(['Sheet ' num2str(sheet)]);"

by :
"for sheet_number=1:sheet
xlsSheet = xlsWorkbook.createSheet(['Sheet ' num2str(sheet_number)]);

Works well for me, but is it reproducible and reliable with different cases or is it the best way to do this ...

Comment only
14 Nov 2013 Guillaume

Thanks again!

Comment only
14 Nov 2013 Alec de Zegher

I highly recommend to use the 'fullfile' command of Matlab to generate paths to directories or files. It allows you to use relative and absolute paths, independent of the operating system.

The error you get is because could not open or store the file in the requested location.

Hope it helps.

Comment only
14 Nov 2013 Guillaume

Thanks Alec!
You're right, my Poi_Library was not loaded. - -'

But after that, I still got an error :

Error using xlwrite (line 286)
Java exception occurred: ~/Documents/Recherche/Etude Course vs Bondissements/Donnees/Fichiers Sujets/Cyril
Schmit2/Analyse Force Cyril Schmit2.xlsx (No such file or directory)
at Method)

Actually, i had recently changed my laptop to the macbook pro and realized that , with MacOS X, the path filename attribution method is not as easy as Windows .

After multiple trial, i realized that the relative mode didn't work with XlWrite. Therefore, the path filename have to be loaded in absolute mode (starting with /User/username/etc.) with MacOS X

Don't know if it's mentioned in the Help section...


P.S: Sorry for my poor english skills.

Comment only
13 Nov 2013 Alec de Zegher

@Guillaume: Thanks.
Yes it is possible to write to any file on your drive. We do it all the time.
The error you get seems to be caused by one of the libraries that is not loaded. I think it is poi-ooxml or poi-ooxml-schemas, but not sure.

Comment only
13 Nov 2013 Guillaume

Very, Very Nice function!!! Thanks for the submission

I would just like to know, is it possible to write on specific path file? I'm working with MACOS X (Mavericks) and when i tried to write in excel spreadsheet out of the matlab path folder the following error appeared :

Error using xlwrite (line 148)
Java exception occurred:
java.lang.NoClassDefFoundError: Could not initialize class org.apache.xmlbeans.XmlBeans
at org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook$Factory.newInstance(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.onWorkbookCreate(
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(

24 Oct 2013 Michael

Michael (view profile)


21 Oct 2013 Alec de Zegher

@ S A: Just add the folder to your Matlab path, and then it will always be loaded by default.
You can access the "Set Path" in the ribbon toolbar of Matlab. Hope it helps!

Comment only
21 Oct 2013 KoenV

KoenV (view profile)

Works great!

15 Oct 2013 S A

S A (view profile)

I have used Matlab for years on a Windows system, and am just starting on a Mac. How do you add this file to your directory? I copied the poi_library folder to my java folder, and added the .jar files to the classpath.txt file. But how do I add xlwrite to the general matlab directory (so that it may be called in any folder as a built-in matlab function)?

Comment only
17 Sep 2013 Dominik

Hi all,
The column index error is due to the Microsoft limitation for *.xls-files (Excel 1997-2003). Just change your specified file extension to *.xlsx to solve the problem.
Thanks Alec for the hint.

04 Sep 2013 Dominik

Hi Alec,
Thanks for the great submission.
However, like Corbin, I am also receiving an error concerning the column size:
"java.lang.IllegalArgumentException: Invalid column index (256). Allowable column
range for BIFF8 is (0..255) or ('A'..'IV')"
Is there a workaround to this?

23 Jul 2013 Alec de Zegher

Hi Robert,
It should normally append the data. It will only overwrite data if your column header matrix is too big or if your cell range is not properly defined.
If you cannot solve it, please send me a mail with a demo code, so I can reproduce it, and I will fix it as soon as possible.

Comment only
20 Jul 2013 Robert

Robert (view profile)

Hi Alec,

Thanks for sharing this excellent code. I just tried to write data and then add column headers but found that xlwrite (as opposed to xlswrite) does not append to an already existing file but rather replaces it. Am I missing something?

Thanks, Robert

07 Jun 2013 Corbin Cunningham

Hi Alec,

I am receiving this error: "Warning: Could not add cell at RY338 because it exceeds the maximum column limit"

What is the limit on the number of columns xlwrite can make and is there a wordaround for that?

Any info would be great!


Comment only
03 Jun 2013 Alec de Zegher

@Klever: You get this error, because you are running an old version of Matlab(2009a) which does not support the tilde (~) operator to ignore outputs of a function. This has only been introduced in Matlab 2009b. You can read more about it on

As a workaround, you could try to modify line 140 in xlwrite from
[~,~,fileExt] = fileparts(filename);
[unusedA,unusedB,fileExt] = fileparts(filename);

Comment only
02 Jun 2013 Klever

Klever (view profile)

Hi Alec, This script seems like it has great potential for my application. However, it works great on Windows, but on Red Hat and with MATLAB 7.8.0 (2009a) I keep getting the following error when I run your test script:

??? Error: File: xlwrite.m Line: 140 Column: 7
Expression or statement is incorrect--possibly unbalanced (, {, or [.

Error in ==> Test_xlWrite at 28
xlwrite(fileName, xlsData, sheetName, startRange);

Can't seem to solve this error. Any Suggestions?

28 May 2013 Alec de Zegher

@Jeremy: This is a bug in the implementation of XLSREAD. When opening an XLSX on a Mac, XLSREAD opens it in 'basic' mode. The 'basic' mode in XLSREAD has a bug when opening XLSX. If you try [~,b,c] = xlsread('myXlsx.xls', 1, '', 'basic') on your windows PC you will see the same bug.
I would recommend to save the file as XLS if possible.

@Barry: There is no plan to create an xlsread version with the POI library. Did you try using the xlsread in 'basic' mode? This should normally avoid the "Could not start Excel server..." error.

Comment only
24 May 2013 Barry

Barry (view profile)

I was just wondering if there is a xlread version using the POI library. When using the normal xlsread in a loop I eventually get a "Could not start Excel server...". Thanks.

09 May 2013 Jeremy

Jeremy (view profile)

Update: I tried this on Windows 7 and it worked correctly. On my Mac(10.8) I encountered the problem. Also this was as a .xlsx, it seems the .xls works as stated.
Hi, I've noticed a bug(s) when trying to use xlsread after xlwrite. In my situation it was occurring when the first column of a record was a '1A' instead of a '1a', but solving this next bug may catch that one. I tried to make a sample program to illustrate the bug. The return did not get the second row on the read. Note: If i go into Excel and do something and resave, xlsread then reads the second row:
titles = {'label1', 'label2'};
record = {1, 2};
xlwrite('myXlsx.xlsx', titles, 'A1:B1');
xlwrite('myXlsx.xlsx', record, 'A2:B2');
[~,b,c] = xlsread('myXlsx.xlsx')
b =
c =

06 May 2013 Tom

Tom (view profile)

great - a little slow - but still great!

10 Apr 2013 Denis Anikiev

Great submission, thanks.
Why don't you add something like this to beginning:

path = mfilename('fullpath');
name = mfilename;
path = path(1:length(path)-length(name));
javaaddpath([path 'poi_library/poi-3.8-20120326.jar']);
javaaddpath([path 'poi_library/poi-ooxml-3.8-20120326.jar']);
javaaddpath([path 'poi_library/poi-ooxml-schemas-3.8-20120326.jar']);
javaaddpath([path 'poi_library/xmlbeans-2.3.0.jar']);
javaaddpath([path 'poi_library/dom4j-1.6.1.jar']);

05 Mar 2013 Alexandre Laurin  
27 Feb 2013 Alec de Zegher

@Mario: Thanks!

@Thierry: thanks for the recommendations!
1) The Stax library should indeed also be loaded. This will be fixed in next release.

2) Originally we also wanted to add an auto-load function, but we ran into the issue that the POI folder location is unknown. It is allowed to be anywhere on your computer. For example in our matlab-webapplications, the POI libraries are put next to the other java libraries in a central folder. To keep it as generic as possible we decided to throw an error if it is not loaded.

3)xlwrite replacing NaN with the previous number is indeed a bug. This was solved in the update of 25/01/2013.

Best Regards,

Comment only
27 Feb 2013 Mario

Mario (view profile)

Hi Alec thanks for this wonderful submission it works great.

19 Feb 2013 Thierry Dalon

1.It seems you also need to javaaddpath the stax*.jar to get it work, right?
(it is omitted in the test_xlwrite).
I would add something like this in the beginning of xlwrite:
if exist('', 'class') ~= 8 ...
% || exist('org.apache.poi.hssf.usermodel.HSSFWorkbook', 'class') ~= 8 ...
% || exist('org.apache.poi.xssf.usermodel.XSSFWorkbook', 'class') ~= 8
% auto-initialize

2. xlwrite replace NaN by previous numeric values
whereas xlswrite replace NaN by empty cell.

Comment only
03 Feb 2013 Alec de Zegher

Hello Jveer,

It should not be a problem to use javaaddpath together with the compiler. We use it for example with de Matlab JA compiler in our company.

To make it work with the compiler:
- Add/drag&drop the POI folder to 'Shared Resource and Helper Files'-window of the compile project
- make sure the javaaddpath point to the right (relative) location.

I hope this helps

Comment only
03 Feb 2013 Jveer

Jveer (view profile)

Thank you for the excellent submission.

Is there a way around 'javaaddpath' in order to compile using Matlab compiler?

26 Jan 2013 Robert

Robert (view profile)

Very nice, many thanks for sharing this. I've added the javaaddpath-commands to my startup.m file - this way xlwrite is immediately available

25 Jan 2013 Alec de Zegher

Hello Klaus, the bug is fixed & also the documentation was adapted. I uploaded a new version. It should be online once accepted by the Mathworks.

Comment only
22 Jan 2013 Klaus

Klaus (view profile)

to get xlswrite behavier for NaN's just insert

if isnumeric(data)
if isnan(data)
if ~isempty(data)

Comment only
22 Jan 2013 Klaus

Klaus (view profile)

using cell arrays the NaN to empty conversion is currently not working.

in the help example xlSwrite is copy-pasted

04 Jan 2013 Wouter

Wouter (view profile)

10 Dec 2012 Marianna

Alec thanks a lot for the immediate feedback! I tried it and it works great, I can't thank you enough :)

Comment only
04 Dec 2012 Alec de Zegher

Hello Marianna,
When you read the documentation of xl(s)write, you are not allowed to give an empty ([]) sheet. You should use the syntax xlwrite('test.xls',M,'A1:B10') instead of xlwrite('test.xls',M,[],'A1').

Setting the sheet to 1 is also an option, like you said... and the error you are getting is a bug:) I fixed it and uploaded a new version today. It should be online by tomorrow.

Comment only
02 Dec 2012 Marianna

Hi and thanks for the much needed submission :)
I have been using the function for some weeks now without problem. Recently I tried to use it in the code of a simple GUI that I implemented and for some reason nothing works..
More specifically, I have o command of the type:
and get the following error:
??? No method 'getSheet' with matching signature found for class

Error in ==> xlwrite at 161
xlsSheet = xlsWorkbook.getSheet(0);

If I set the sheet to 1, I get:
??? Java exception occurred:
java.lang.IllegalArgumentException: Sheet index (0) is out of range (0..-1)

Note that everything works fine when I save my variables in the workspace and use the same code from the command line (so it obviously has to do with the GUI).

Any idea if/how I can work around this?

Any help would be much appreciated!

Comment only
27 Nov 2012 Alec de Zegher

@ Dan & Jason: Thanks for the feedback!

I fixed the bug & uploaded a new version. Should be approved by tha Mathworks soon...

Comment only
27 Nov 2012 Dan

Dan (view profile)

Excellent job!

I had the same problem mentioned by Jason. I replaced line 211 by:

currentRow = xlsSheet.getRow(iRow);
if isempty(currentRow)
currentRow = xlsSheet.createRow(iRow);

Hope it helps!

20 Nov 2012 Jason

Jason (view profile)

When I try to specify a range, it wipes out the entire row. So for example the following code


writes the data in the proper cells but all of the other cells of row 5 are overwritten to be blank. Is there a way to preserve the data in the other cells?

Comment only
06 Nov 2012 omar

omar (view profile)

problem solved, xlsread(fileName) works. Great job, thanks a millon.

05 Nov 2012 Alec de Zegher

the problem should be solved with this update (for XLS files).

Comment only
28 Oct 2012 omar

omar (view profile)


How to read the file again in matlab

xlsread give the following:

Error using xlsread (line 232)
XLS File contains unicode text which is not yet

Any suggestions?

Thanks in advance

28 Oct 2012 omar

omar (view profile)

28 Oct 2012 omar

omar (view profile)

Your code just worked on Linux ubuntu with MATLAB 2011b.Thanks

17 Oct 2012 Marin Deresco


Comment only
12 Oct 2012 peter

peter (view profile)

Now I got it !!!
thanks a lot

12 Oct 2012 Alec de Zegher

@ Peter

This error is caused because the jxl.jar (JExcelApi) package is not loaded correctly in your workspace.

- Check that you extracted correctly the jxl.jar file from the zip file.
- You should not forget to add the jxl.jar file to your Matlab Java path as explained in test_xlwrite. If jxl.jar is in the same directory as your current workspace: you should execute the "javaaddpath('jxl.jar');" command. If jxl.jar is not in the same directory as your current workspace, you should execute the "javaaddpath('\FULL\PATH\TO_jxl.jar');".

Please let me know if this solves your problem or not.


Please let me know

Comment only
12 Oct 2012 peter

peter (view profile)

??? Undefined variable "jxl" or class "jxl.Workbook.createWorkbook".

I tried to run the test_xlwrite and got the following ?

Error in ==> xlwrite at 87
xlsWorkbook = jxl.Workbook.createWorkbook(xlsFile);

Error in ==> test_XLWRITE at 19
xlwrite(fileName, xlsData, sheetName, startRange);

Comment only
05 Nov 2012 1.1

The new version of xlwrite uses the Apache POI library, instead of JExcelApi. The Apache POI library has some advantages over JExcelApi library:
- It can create XLSX files
- xlsread supports xls files generated by POI lib.

28 Nov 2012 1.5

Fixed bug: use existing rows if present, instead of overwrite rows by default. Thanks to Dan & Jason.

28 Nov 2012 1.2

Fixed bug: use existing rows if present, instead of overwrite rows by default. Thanks to Jason.

04 Dec 2012 1.6

Bugfix: if a numeric sheet was given & didn't exist an error was returned instead of creating the sheet. Thanks to Marianna

07 Jan 2013 1.7

Fixed bug: use existing cell if present, instead of overwriting. This way original XLS formatting is kept & not overwritten.

25 Jan 2013 1.8

20130125 - Fixed bug & documentation. Incorrect working of NaN. Thanks Klaus

27 Feb 2013 1.9

20130227 - Fixed bug when no sheet number given & added Stax to java load. Thanks to Thierry

Contact us