write excel file to many folders in directory using matlab - excel

I need to write an excel file to many folders ( folder* ) under D:\ and loop over them to further process individually.
i tried the following code for long time ..
srcFolders = dir('D:\folder*');
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
xlswrite('srcFolders\filename.xls', srcFolders(folder).name,'Sheet1', folder_range);
end

I'm assuming that you want to write different sets of data to a Excel file and were just having some trouble. If that's not accurate comment and let me know.
%Just generating some arbitrary data
data = arrayfun(#(m,n) rand(m,n), randi(50, 9, 1), randi(50, 9, 1), 'uni', 0);
%The base file path
path = 'D:';
%The pattern used to choose the folders
folderPattern = 'folder*';
%The files you want to write to
srcFiles = {'A', 'B', 'D'};
%And the extension
ext = '.xlsx';
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
srcFolders = fullfile(path, {srcFolders.name});
%Construct the full file path
fullPath = cellfun(#(f) fullfile(f, strcat(srcFiles(:), ext)), srcFolders, 'uni', 0);
fullPath = vertcat(fullPath{:});
%Write the data to the files
for i = 1:length(fullPath)
xlswrite(fullPath{i}, data{i})
end
Edit:
Based on OP's feed.
Note for the second overhaul. I didn't test this and I'm done. This was way to much for a single question and you are abusing the way this website is supposed to work.
%The base file path
path = 'D:';
%Relative reference to reference images
ImageRefLocations = {'Ref\RefI1.jpg', 'Ref\RefI2.png', 'Ref\RefI3.jpg'};
%Base Image location
baseImage = fullfile(path, ImageRefLocations(:));
%The pattern used to choose the folders
folderPattern = 'folder*';
%The image extension
[~, ~, ext] = unique(cellfun(#(f) fileparts(f), baseImage, 'uni', 0));
%The excel extension
ExcelExt = '.xlsx';
msg = {' = no'; ' = ok'};
i0 = cellfun(#(f) imread(f), baseImage, 'uni', 0);
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
isDir = [srcFolders.isdir];
srcFolders = {srcFolders(isDir).name}';
PathedFolders = fullfile(path, srcFolders);
excelFiles = fullfile(path, strcat(srcFolders, ExcelExt));
for i = 1:length(PathedFolders)
f = PathedFolders{i};
Images = cellfun(#(x) dir(fullfile(f, ['*', x])), ext, 'uni', 0);
Images = vertcat(Images{:});
if isempty(Images)
continue
end
Images = {Images.name}';
[~, ImageNames, ~] = cellfun(#(x) fileparts(x), Images, 'uni', 0);
ImageList = fullfile(f, Images);
match = zeros(size(ImageList));
for j = 1:length(ImageList)
image = imread(ImageList{j});
for k = 1:length(i0)
if ~all(size(image) == size(i0{k}))
continue
end
match(j) = all(image(:) == i0{k}(:));
if match(j)
continue
end
end
end
matchMessage = strcat(Images, msg(match + 1));
xlswrite(excelFiles{i}, matchMessage)
end

Related

Renaming all the files in a folder is renaming the sub folders too

When try to rename the files in a specific folder, the program code renames
all the sub folders too. Is there a way to fix it?
dname = input("\nenter the path\t")
if os.path.isdir(dname):
dst = input("\nenter new file name: \t")
n = 1
for i in os.listdir(dname):
if not os.path.isdir(i):
mystr = ".txt"
src = os.path.join(dname, i)
dd = dst + str(n) + mystr
dd = os.path.join(dname, dd)
os.rename(src, dd)
n += 1
Yours "isdirectory" (os.path.isdir(i)) check doesn't seem to work.
You can precompile the list of files present in the directory using the below code,
files = (file for file in os.listdir (dname)
if os.path.isfile ( os.path.join ( dname, file) ))
And then directly iterate over the files, like,
for i in files:
mystr = ".txt"
src = os.path.join(dname, i)
dd = dst + str(n) + mystr
dd = os.path.join(dname, dd)
os.rename(src, dd)
n += 1
You can also have a look at this answer, which lists all the ways in which you can list files in a given directory.
Link: https://stackoverflow.com/a/14176179/10164003
Thanks
It seems below the line isn't working for you.
os.path.isdir(i)
Try out creating the full path before checking :
os.path.isdir(os.path.join(dname, i)):

compare multi images with all images in referenced folders using matlab

I have some reference image (I'll call this images as Ref\animal.jpg', 'Ref\food.jpg', 'Ref\gon.jpg ... etc ). Then in each folder i want to compare Image1, Image2, ..., ImageN to each referenced image . I want to summarize the results of the comparison by writing to an Excel file (which has the same name as the folder) (in A1) 'Image 1 = ok', (in B1) 'Image 2 = no', ..., (in the Nth row, 1st column) 'Image N = ok'.
i got the following error , when i use single image its working well but multi images in reference images ( second line ) i got cellfun error .
Error using cellfun
Input #2 expected to be a cell array, was double instead.
any one please can correct the following code ??
%The base file path
path = 'D:';
% Relative reference to reference images
ImageRefLocations = {'Ref\RefI1.jpg', 'Ref\RefI2.png', 'Ref\RefI3.jpg'};
%Base Image location
baseImage = fullfile(path, ImageRefLocations(:));
%The pattern used to choose the folders
folderPattern = 'folder*';
%The image extension
[~, ~, ext] = unique(cellfun(#(f) fileparts(f), baseImage, 'uni', 0));
%The excel extension
ExcelExt = '.xlsx';
msg = {' = no'; ' = ok'};
i0 = cellfun(#(f) imread(f), baseImage, 'uni', 0);
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
isDir = [srcFolders.isdir];
srcFolders = {srcFolders(isDir).name}';
PathedFolders = fullfile(path, srcFolders);
excelFiles = fullfile(path, strcat(srcFolders, ExcelExt));
for i = 1:length(PathedFolders)
f = PathedFolders{i};
after this line i got error ...
Error using cellfun
Input #2 expected to be a cell array, was double instead.
Images = cellfun(#(x) dir(fullfile(f, ['*', x])), ext, 'uni', 0);
Images = vertcat(Images{:});
if isempty(Images)
continue
end
Images = {Images.name}';
[~, ImageNames, ~] = cellfun(#(x) fileparts(x), Images, 'uni', 0);
ImageList = fullfile(f, Images);
match = zeros(size(ImageList));
for j = 1:length(ImageList)
image = imread(ImageList{j});
for k = 1:length(i0)
if ~all(size(image) == size(i0{k}))
continue
end
match(j) = all(image(:) == i0{k}(:));
if match(j)
continue
end
end
end
matchMessage = strcat(Images, msg(match + 1));
xlswrite(excelFiles{i}, matchMessage)
end

Writing to Excel sheet based on image difference using matlab

I have some folders named test* from test 1 to test 100 for example, I need to print names of folders as header in first row.
Then I need to check my test image image2 with each image inside these folders if the diff bigger than 0.05 between my test image2 and every images from each folder test* will write 1 otherwise write 0. till to testn.
My code is as follow :
srcFolders = dir('D:\test*');
for folder = 1:length(srcFolders)
path = strcat('D:\',srcFolders(folder).name);
sear = strcat(path, '\*.bmp');
srcFiles = dir(sear);
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
Image1= imread(filename);
Image2 = imread('D:\2','jpeg'); % Image 2
x = diff( Image2 , Image1)
% any suggestion here to get my output for printing in excel
if (x >= 0.05)
xlswrite(xlsfile, srcFiles(i), ‘0’, ‘A1’);
else
xlswrite(xlsfile, srcFiles(i), ‘1’, ‘A1’);
end
end
end
thanks
%On every 'folder loop', increment the column range so you have 1 column by folder
%On every 'file loop', increment the row range so you have 1 row by file
xls_filename = 'foo.xls'; %The name of your xls file
xls_sheet = 'sheet_name'; % Put here the name of the sheet you want to write in
column_range = 'A' % Initialisation of the column range
srcFolders = dir('D:\test*');
for folder = 1:length(srcFolders)
path = strcat('D:\',srcFolders(folder).name);
folder_range = strcat(column_range, '1');
xlswrite(xls_filename, {srcFolders(folder).name}, xls_sheet, folder_range); %Writing the name of the folder in the first row
sear = strcat(path, '\*.bmp');
srcFiles = dir(sear);
row_range = '2';
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
Image1= imread(filename);
Image2 = imread('D:\2','jpeg');
x = diff( Image2 , Image1);
file_range = strcat(column_range, row_range);
if (x >= 0.05)
xlswrite(xls_filename, {'0'}, xls_sheet, file_range ); %Writing '0' in the second row
else
xlswrite(xls_filename, {'1'}, xls_sheet, file_range ); %Writing '1' in the second row
end
row_range = char(row_range + 1); %Moving to the next row
end
column_range = char(column_range + 1); %Moving to the next column
end

matlab automatically save excel file using activex interface

I have a code in matlab. After I have run my program, a file 'example2.xlsx' was created.
Now I have the code below and I want matlab to replace the current 'example2.xlsx' by the new 'example2.xlsx' (saving automatically without asking me if I want to replace it):
e = actxserver ('Excel.Application'); % # open Activex server
filename = fullfile(pwd,'example2.xlsx'); % # full path required
ewb = e.Workbooks.Open(filename); % # open the file
esh = ewb.ActiveSheet;
str = num2str(num_rows+1);
esh.Range(strcat('J',str)).Interior.Color = clr;
sheet1 = e.Worksheets.get('Item', 'Sheet1');
range1 = get(sheet1,'Range', strcat('A',str),strcat('I',str));
range1.Value = values{num_rows+1};
[num, txt, raw] = xlsread('example2.xlsx');
num_rows = length(num(:,1));
xlWorkbookDefault = 51; % # it's the Excel constant, not sure how to pass it other way
ewb.SaveAs(fullfile(pwd,'example2'), xlWorkbookDefault)
ewb.Close(false)
e.Quit
e.delete
You can set the DisplayAlerts property of the Excel application object to false to stop these dialogs from appearing.
The following is a simplified version of your code:
e = actxserver ('Excel.Application'); % # open Activex server
filename = fullfile(pwd,'example2.xlsx'); % # full path required
ewb = e.Workbooks.Open(filename); % # open the file
esh = ewb.ActiveSheet;
sheet1 = e.Worksheets.get('Item', 'Sheet1');
range1 = get(sheet1,'Range', 'A1');
range1.Value = 3;
set(e, 'DisplayAlerts', 0); % # Stop dialog!
xlWorkbookDefault = 51; % # it's the Excel constant, not sure how to pass it other way
ewb.SaveAs(fullfile(pwd,'example2'), xlWorkbookDefault)
ewb.Close(false)
e.Quit
e.delete

Script to rename and copy files to a new directory.

Hi I have recently made this script to rename files I scan for work with a prefix and a date. It works pretty well however it would be great if it could make a directory in the current directory with the same name as the first file then move all the scanned files there. E.g. First file is renamed to 'Scanned As At 22-03-2012 0' then a directory called 'Scanned As At 22-03-2012 0' (Path being M:\Claire\Scanned As At 22-03-2012 0) is made and that file is placed in there.
I'm having a hard time figuring out the best way to do this. Thanks in advance!
import os
import datetime
#target = input( 'Enter full directory path: ')
#prefix = input( 'Enter prefix: ')
target = 'M://Claire//'
prefix = 'Scanned As At '
os.chdir(target)
allfiles = os.listdir(target)
count = 0
for filename in allfiles:
t = os.path.getmtime(filename)
v = datetime.datetime.fromtimestamp(t)
x = v.strftime( ' %d-%m-%Y')
os.rename(filename, prefix + x + " "+str(count) +".pdf")
count +=1
Not quite clear about your requirement. If not rename the file, only put it under the directory, then you can use the following codes (only the for-loop of your example):
for filename in allfiles:
if not os.isfile(filename): continue
t = os.path.getmtime(filename)
v = datetime.datetime.fromtimestamp(t)
x = v.strftime( ' %d-%m-%Y')
dirname = prefix + x + " " + str(count)
target = os.path.join(dirname, filename)
os.renames(filename, target)
count +=1
You can check help(os.renames).

Resources