How to avoid trimming of string cells got by readtable method?
Show older comments
Hello, everyone,
I am working with spreadsheet tables, which I import by readtable method. I have several numeric columns, but my crucial point is the column with strings. The readtable function trim every string (removes leading and trailing whitespace). However, I need to avoid this trimming and leave the strings as they are. I tried to look into documentation, but found only the trimming related to tables originating from text files.
My current code related to this looks following:
mytable=readtable(filename,'Sheet',sheetname,'NumHeaderLines',0)
Do you have any suggestions?
4 Comments
Cris LaPierre
on 19 Aug 2025
Can you share an example file that, when running the code you shared, produces the issue you describe?
tTest=readtable('tst.xlsx','readvariablenames',0)
where the actual data in the spreadsheet are ' dog ' and ' cat'
This is setvaropts: <documented default behavior> for the 'WhiteSpaceRule' parameter for text variables (albeit it takes a fair amount of digging to get down that far given the veritable plethora of options <grin>)
Were you thinking there would/should be some other behavior?
Cris LaPierre
on 19 Aug 2025
No, I was just trying to avoid creating my own test dataset.
dpb
on 19 Aug 2025
We're all lazy, aren't we? <vbg>
I thought mayhaps you were getting ready to show us some magic!
Accepted Answer
More Answers (1)
filename='tst.xlsx';
opts = spreadsheetImportOptions(DataRange='A1');
opts=setvaropts(opts,WhiteSpaceRule='preserve');
mytable=readtable(filename,opts)
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!