MATLAB: Save multiple tables in Excel using a while loop - excel

I have the following while loop in which an image is read and analyzed, then the results are saved in a table, that is saved in an Excel worksheet. I initially did this code for one single image/table, then realized I need to develop it for n images.
I basically want the results to be saved in the same Excel worksheet without overwriting, ideally the tables are vertically separated by an empty row.
Here's my effort as for now:
while(1)
...
%code code code
...
message = sprintf('Do you want to save the results in an Excel
worksheet?');
reply = questdlg(message,'Run Program?','OK','Cancel', 'OK');
if strcmpi(reply, 'Cancel')
% User canceled so exit.
return;
end
% Table creation.
% code code code
% Saving table to Excel
T = table(Diameter,BandWidth,n1,n2,P1,P2,Damage,...
'RowNames',Band);
filename = 'Results.xlsx';
writetable(T, filename, 'Sheet',1, 'Range', 'A1','WriteRowNames',true);
% Create a while loop to save more experiments to the Excel worksheet.
promptMessage = sprintf('Do you want to process another photo?');
button = questdlg(promptMessage, 'Continue', 'Continue', 'Cancel',
'Continue');
if strcmpi(button, 'Cancel')
break;
end
end
If it can help you to get an idea, each table is a 6x8.

Prior to your while loop, declare a cell array to hold the table that you will eventually write to an excel file.
cellArrayOfTableToBeWritten = {};
Also prior to the loop, define a cell array that will serve as a blank row.
rowWidth = 8;
blankrow = repmat({''},1,rowWidth);
Where you currently write the table, instead add what you would have written to the cell array with a blank row at the bottom.
cellArrayOfTableToBeWritten = [cellArrayOfTableToBeWritten;
T.Properties.VariableNames;
table2cell(T);
blankrow];
Once your while loop is done, write the combined cell array to a file as an excel file.
xlswrite(filename, cellArrayOfTableToBeWritten);

Related

Python3 - Openpyxl - For loop to search through Column - Gather information Based on position of first cell location

UPDATE!
My goal is to modify an existing Workbook ( example - master_v2.xlsm ) and produce a new workbook (Newclient4) based on the updates made to master_v2.
I'm using a single sheet within master_v2 to collect all the data which will be determining what the new workbook will be.
Currently using multiple if statements to find the value of the cells in this "repository" sheet. Based on specific cells, I'm creating and adding values to copies of an existing sheet called "PANDAS".
My goal right now is to create a dict based on two columns. The loop through
the keys so that every time I get a hit on a cell, I will gather values from specific keys.
That's listed below:
from openpyxl import load_workbook
# Start by opening the spreadsheet and selecting the main sheet
workbook = load_workbook(filename="master_v2.xlsm",read_only=False, keep_vba=True)
DATASOURCE = workbook['repository']
DATASOURCE["A:H"]
cell100 = DATASOURCE["F6"].value
CREATION = cell100
cell101 = DATASOURCE["F135"].value
CREATION2 = cell101
cell107 = DATASOURCE["F780"].value
CREATION7 = cell107
if CREATION.isnumeric():
source = workbook['PANDAS']
target = workbook.copy_worksheet(source)
ss_sheet = target
ss_sheet.title = DATASOURCE['H4'].value[0:12]+' PANDAS'
if CREATION2.isnumeric():
source = workbook['PANDAS']
target = workbook.copy_worksheet(source)
ss_sheet = target
ss_sheet.title = DATASOURCE['H133'].value[0:12]+' PANDAS'
if CREATION3.isnumeric():
source = workbook['PANDAS']
target = workbook.copy_worksheet(source)
ss_sheet = target
ss_sheet.title = DATASOURCE['H262'].value[0:12]+' PANDAS'
else:
print ("no")
workbook.save(filename="NewClient4.xlsm")
Instead of the many if statements I was hoping to be able to loop through the column as explained above,
once I found my value, gather data and copy it over to a copy of sheet which is then filled out by other cells. Each time the loop comples, I want to do repeat on the next match of the string.. but I'm only this far and it's not quite working.
Anyone have a way to get this working?
( trying to replace the many one to one mappings and if statements )
for i in range(1,3000):
if DATASOURCE.cell(row=i,column=5).value == "Customer:":
source = workbook['Design details']
target = workbook.copy_worksheet(source)
ss_sheet = target
ss_sheet.title = DATASOURCE['H4'].value[0:12]+' Design details'
else:
print ("no")
Thank you guys in advanced

How to loop through excel sheets, perform calculations, and compile results

I have roughly 70,000 sheets that all have to have calculations done, and then all results compiled into a new sheet (which would be 70,000 lines long).
It needs to be sorted by date.
I'm VERY very very poor at matlab, but I've what I need the script to do for each excel sheet, I'm just unsure how to make it do them for all.
Thank you!!! (I took out some of the not important code)
%Reading in excel sheet
B = xlsread('24259893-008020361800.TorqueData.20160104.034602AM.csv');
%Creating new matrix
[inYdim, inXdim] = size(B);
Ydim = inYdim;
[num,str,raw]=xlsread('24259893-008020361800.TorqueData.20160104.034602AM.csv',strcat('A1:C',num2str(Ydim)));
%Extracting column C
C=raw(:,3);
for k = 1:numel(C)
if isnan(C{k})
C{k} = '';
end
end
%Calculations
TargetT=2000;
AvgT=mean(t12);
TAcc=((AvgT-TargetT)/TargetT)*100 ;
StdDev=std(B(ind1:ind2,2));
ResTime=t4-t3;
FallTime=t6-t5;
DragT=mean(t78);
BreakInT=mean(t910);
BreakInTime=(t10-t9)/1000;
BreakInE=BreakInT*BreakInTime*200*.1047;
%Combining results
Results=[AvgT TAcc StdDev ResTime FallTime DragT BreakInT BreakInTime BreakInE]
I think I need to do something along the lines of:
filenames=dir('*.csv')
and I found this that may be useful:
filenames=dir('*.csv');
for file=filenames'
csv=load(file.name);
with stuff in here
end
You have the right idea, but you need to index your file names in order to be able to step through them in the for loop.
FileDir = 'Your Directory';
FileNames = {'Test1';'Test2';'Test3'};
for k=1:length(FileNames)
file=[FileDir,'/',FileNames{k}]);
[outputdata]=xlsread(file,sheet#, data locations);
THE REST OF YOUR LOOP, Indexed by k
end
How you choose to get the file names and directory is up to you.

Matlab: writing multiple tables with cell2table

I would like to write multiple tables in a matlab for loop. As an input i use a excel file that contains multiple sheets. Yhe amount of sheets and the size of the data is not prefixed. The reading of this files goes right but once i save it to a table it overwrites the same table over and over again.
The clue would be a flexible name in the cell2table function. I have these names in sheetname (all) and Sheet (current). Does anyone has a suggestion?
[type,sheetname] = xlsfinfo('\Matlab\dienstregeling.xlsx');
m=size(sheetname,2);
for(i=1:m);
Sheet = char(sheetname(1,i));
[num, text, raw] = xlsread('\Matlab\dienstregeling.xlsx',Sheet);
test = cell2table(raw);
end
You could use a structure and generate the field names from the variable Sheet:
test = struct;
for(i=1:m);
Sheet = char(sheetname(1,i));
[num, text, raw] = xlsread('\Matlab\dienstregeling.xlsx',Sheet);
test.(Sheet) = cell2table(raw);
end

How to import lots of data into matlab from a spreadsheet?

I have an excel spreadsheet with lots of data that I want to import into matlab.
filename = 'for_matlab.xlsx';
sheet = (13*2)+ 1;
xlRange = 'A1:G6';
all_data = {'one_a', 'one_b', 'two_a', 'two_b', 'three_a', 'three_b', 'four_a', 'four_b', 'five_a', 'five_b', 'six_a', 'six_b', 'seven_a', 'seven_b', 'eight_a', 'eight_b', 'nine_a', 'nine_b', 'ten_a', 'ten_b', 'eleven_a', 'eleven_b', 'twelve_a', 'twelve_b', 'thirteen_a', 'thirteen_b', 'fourteen_a'};
%read data from excel spreadsheet
for i=1:sheet,
all_data{i} = xlsread(filename, sheet, xlRange);
end
Each element of the 'all_data' vector has a corresponding matrix in separate excel sheet. The code above imports the last matrix only into all of the variables. Could somebody tell me how to get it so I can import these matrices into individual matlab variables (without calling the xlsread function 28 times)?
You define a loop using i but then put sheet in the actual xlsread call, which will just make it read repeatedly from the same sheet (the value of the variable sheet is not changing). Also not sure whether you intend to somehow save the contents of all_data, as written there's no point in defining it that way as it will just be overwritten.
There are two ways of specifying the sheet using xlsread.
1) Using a number. If you intended this then:
all_data{i} = xlsread(filename, i, xlRange);
2) Using the name of the sheet. If you intended this and the contents of all_data are the names of sheets, then:
data{i} = xlsread(filename, all_data{i}, xlRange); %avoiding overwriting

How to modify xlsread to get a step-by-step updated flag from loading process

I have installed Matlab r2010a on my computer
I need use the function xlsread to load data from one just one *.xls or *.xlsx file. that's not a big challenge, the problem is How to modify xlsread.m to get a flag (integer) that gives the percentage of the loading process?
Thanks a lot.
so far i made this:
put a step variable to count until half then call xlsread that take a little time and after load process, the counter in 49.5% count to the end.
Not the best, but this is what I have
file = 'example.xls';
h = waitbar(0, ['Loading data from ' file], ...
'Name', 'Loading',...
'CreateCancelBtn',...
'setappdata(gcbf, ''canceling'', 1)');
steps = 200;
for step = 1 : steps
%# Check for Cancel button press
if getappdata(h, 'canceling')
okCancel = 1;
break
end
pause(0.01); %# Delay time for wait bar progres
if step == steps/2
[data, txt] = xlsread(file);
end
%# Process status report
waitbar(step/steps, h, sprintf(['Loading data from file... %3.2f%%'], step*100/steps));
end
set(h, 'CloseRequestFcn', 'closereq')
close(h)
XLSREAD function allows you to specify ranges of cells to read. Therefore you could read your data in batches (say read the first 50 rows of the table, then the next 50, and so on), each time "incrementing" the progress bar.
Note that this will be slower than reading the whole table at one, because the function has to make a connection to Excel COM then tear it down each time it is called (see this post for an explanation and a possible solution).
EDIT:
Here is a quick example:
%# path to excel file to read
fname = fullfile(pwd,'test.xls');
%# get number of rows/columns in table
Excel = actxserver('Excel.Application'); %# open Excel COM Server
wb = Excel.Workbooks.Open(fname, 0, true); %# open XLS file for reading
sheet = Excel.Worksheets.get('item',1); %# activate first sheet
numRows = sheet.Range('A1').End('xlDown').Row;
numCols = sheet.Range('A1').End('xlToRight').Column;
wb.Close(false); %# close XLS file
Excel.Quit(); %# cleanup
Excel.delete();
clear Excel wb sheet;
%# read rows in steps, and show progress-bar
numSteps = 20;
idx = fix(linspace(0,numRows,numSteps+1));
num = cell(numSteps,1);
h = waitbar(0, 'Reading excel file');
for i=1:numSteps
%# update progress-bar
waitbar(i / numSteps);
%# range of cells to read
cellRange = sprintf('%c%d:%c%d', ...
'A', idx(i)+1, char('A'+numCols-1), idx(i+1));
num{i} = xlsread(fname, 1, cellRange);
end
close(h)
%# merge all cells into a matrix
num = cell2mat(num);
This assumes the Excel file contains a table of numeric data. Feel free to adapt to your own file.

Resources