Stuart’s MATLAB Videos

Watch and Learn

Creating a Function to Save a Table to a CSV File if it’s Too Big for Excel

Posted by Stuart McGarrity,

I often save tables to Excel for sharing with others, but if the data is too large, I need to share to a CSV file instead. Here I build a function to do that. Features covered in this code-along style video include:

  • writetable
  • regexprep

Note, at @18:13 I think I’m looking at the Excel file and don’t understand the first sheet name, but I’m actually looking at the CSV file and the sheet name defaults to the filename. You can ignore my floundering for the remaining 5 min of the video if you like.

Follow me (@stuartmcgarrity) if you want to be notified via Twitter when I post.

Play the video in full screen mode for a better viewing experience. 

Here is the code. I had to correct the possible Excel filename endings to .xls, .xlsx, or .xlsm.

function mywritetable(tableData,fileName,sheetName)
% Writes table to Excel by default, but writes to CSV if too big and
% appends sheetName to fileName

maxRows=1e6;
if height(tableData) <  maxRows
    % Default: Write to Excel (assume xls, xlsx, or xlsxm extension)
    writetable(tableData,fileName,'Sheet',sheetName);
else    
    % If too big: Write to a CSV file
    fileName=regexprep(fileName,'(.xls|.xlsx|.xlsm)$',['_' sheetName '.csv']);
    writetable(tableData,fileName);    
end

Add A Comment

What is 3 + 9?

Preview: hide