필터 지우기
필터 지우기

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

조회 수: 4 (최근 30일)
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...

채택된 답변

Star Strider
Star Strider 2023년 12월 11일
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
Caitlin
Caitlin 2023년 12월 14일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by