Clear Filters
Clear Filters

How do I keep original headers when bulk converting CSV files to Excel and deleting everything except for three columns?

4 views (last 30 days)
Hi all, I want to write a matlab code that takes a CSV file, transforms it into an excel file under the same name and pulls only the three columns I want. It does that for all the files in a folder, then it throws them into a new folder. I have one that works great, but unfortunately Matlab renames the columns "Var4" Var5" Var6." Does anyone know how to keep the original headers? In theory, the headers should be the same for all the files but its a good back-check to keep the original when the data is visualized (and the headers become axes) later.
Below is my current code with commented out explanations.
% Specify the directory containing CSV files
csvDirectory = 'C:\\Users\\Myname\\Documents\\MATLAB\\playground';
% Create a subfolder for the Excel files
outputFolder = fullfile(csvDirectory, 'ExcelOutput');
mkdir(outputFolder);
% Get a list of CSV files in the directory
csvFiles = dir(fullfile(csvDirectory, '*.csv'));
% Iterate over each CSV file
for i = 1:length(csvFiles)
% Get the current CSV file name
csvFileName = fullfile(csvDirectory, csvFiles(i).name);
% Read the CSV file
data = readtable(csvFileName);
% Extract the specified columns (4, 5, 6) along with headers
selectedData = data(:, [4, 5, 6]);
% Specify the new Excel file name
% excelFileName = strrep(csvFileName, '.csv', '.xlsx');
% Specify the new Excel file name in the subfolder
excelFileName = fullfile(outputFolder, [strrep(csvFiles(i).name, '.csv', '_modified.xlsx')]);
% Write the selected data to an Excel file with headers
writetable(selectedData, excelFileName, 'WriteVariableNames', true);
disp(['Excel file "', excelFileName, '" created successfully.']);
end
*update*: the above code was working and now I get an "Error using mkdir. Access is denied." error...

Accepted Answer

Star Strider
Star Strider on 11 Dec 2023
With respect to getting the original headers (variable names), with readtable use 'VariableNamingRule','preserve' (in earlier versions this was 'PreserveVariableNames',true). It should then write them correctly. If you are still having problems with them in that respect, you can get them as a separate cell array with:
VN = TableName.Properties.VariableNames;
and then work with that as well.
Beyond that, it would help to have a representative file to experiment with.
  4 Comments
Caitlin
Caitlin on 14 Dec 2023
Worked! Took me a long while to figure out how to get that to iterate so I could do many files at once (matlab did NOT like these tables). But super helpful! Appreciate the commented out descriptions too... very much so a beginner.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!