Readtable / writematrix / Excel file - how to control the format of variables in the table ?
Mostra commenti meno recenti
I am designing an app which read and/or update an excel file.
When I use the function readtable to import an Excel file, I can not control the format of the variables inside the table.
Indeed, my code to import the table is:
T = readtable("example.xls", "TextType","string")
Also, I use the function writematrix to update the same excel file:
writematrix(var, "example.xls", "Range","C6")
var is string or double types, however, the table shows sometimes string or double type, whereas there should be only string type
I also use actxserver to insert new lines in the excel file, and then fill the new lines with writematrix
e = actxserver('Excel.Application');
rg = ws.Range(ILine);
rg.Insert(-4121);
e.ActiveWorkBook.Close(true)
Quit(e);
delete(e);
I suspect actxserver or writematrix to be the cause of changing the format of the variables via readtable but I am not sure despite my investigations.
Thanks for your help
Risposta accettata
Più risposte (3)
Benjamin Kraus
il 3 Ago 2021
The readtable command takes an optional options input which can be used to control how the XLS file is imported.
T = readtable(filename,opts)
I also recommend trying the Import Tool, as it can help you to customize the options used when importing data from a spreadsheet.
It is hard to be more specific without details about the format of the XLS file. Can you attach a copy of example.xls to this question?
For the reading part, there's an example that's fairly similar to this on the readtable documentation page entitled "Detect and Use Import Options for Spreadsheet Files"
The basic strategy is:
- Use detectImportOptions to create the default options object. This will include various options, including the variable types that MATLAB will import to (in VariableTypes)
- Change VariableTypes to the types to what you want.
- Use the modified options when you import.
I tested this with a little experiment xlsx file, attached, and the following code:
opts = detectImportOptions('example.xlsx');
opts.VariableTypes{1} = 'uint8';
opts.VariableTypes{2} = 'string';
data=readtable('example.xlsx', opts);
class(data.val1)
class(data.val2)
Marc Servagent
il 4 Ago 2021
0 voti
Categorie
Scopri di più su Spreadsheets in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!