Matlab number of rows in excel file - excel

is there a command of Matlab to get the number of the written rows in excel file?
firstly, I fill the first row. and then I want to add another rows in the excel file.
so this is my excel file:
I tried:
e = actxserver ('Excel.Application');
filename = fullfile(pwd,'example2.xlsx');
ewb = e.Workbooks.Open(filename);
esh = ewb.ActiveSheet;
sheetObj = e.Worksheets.get('Item', 'Sheet1');
num_rows = sheetObj.Range('A1').End('xlDown').Row
But num_rows = 1048576, instead of 1.
please help, thank you!

If the file is empty, or contains data in only one row, then .End('xlDown').Row; will move to the very bottom of the sheet (1048576 is the number of rows in a Excel 2007+ sheet).
Test if cell A2 is empty first, and return 0 if it is.
Or use Up from the bottom of the sheet
num_rows = sheetObj.Cells(sheetObj.Rows.Count, 1).End('xlUp').Row
Note: I'm not sure of the Matlab syntax, so this may need some adjusting

You can use MATLAB's xlsread function to read in the spreadsheet. This obtains the following fields:
[numbers strings misc] = xlsread('myfile.xlsx');
if you do a size check on strings or misc, this should give you the following:
[rows columns] = size(strings);
testing this, I got rows = 1, columns = 10 (assuming nothing else was beyond 'A' in the spreadsheet).

Related

Put Excel columns in an array Matlab

I have never used Excel parser in MatLab. I have an Excel file which has 3 columns. And I would like to save all elements of column 2 in an column array and all elements of column 3 in an other column array. How can I browse the Excel file column by column and then line by line?
It works with this :
[~,~,data] = xlsread('excelfile.xlsx');
% Save columns
arraycolumn2 = data(:,2); % Parse column 2
arraycolumn3 = data(:,3); % Parse column 3
You can use function importdata
data = importdata('yourExcelFile.xlsx');
colum1 = data(:,1);
colum2 = data(:,2);
colum3 = data(:,3);

Looping in Matlab to batch process Excel files

I know how to read in multiple Excel files, but am struggling to conduct the same analysis on all of those files. The analysis requires I average some values in different columns, then print those average values to a separate Excel sheet. I can do this with one Excel file, but have trouble figuring out how to print each average value in a different row in the output Excel file. Here is the code I have that works for one file (reads it, averages values in column 4, then prints to a separate Excel file):
data = xlsread('test_1.xlsx');
average_values_1 = data(:,4);
a = [average_values_1];
data_cells = num2cell(a);
column_header ={'Average Value 1'};
row_header(1,1) ={'File 1'}
output = [{' '} column_header; row_header data_cells];
xlswrite('Test Averages.xls', output);
How might I do this over and over again while printing values from each file in the output file as its own table? I suspect a nested loop is in my future.
Thanks in advance.
Here is working example of what you possibly want to do with xlswrite[‍1]:
filename = 'testdata.xlsx'; % Filename to save average values in
for k = 1:10 % Looping for 10 iterations
sheet = 2; % Selecting sheet2
Avg = randi([1 10],1,1); % Generating a random average each time the loop is run
xlRange = char(64+k); % 65 is the ASCII value of A
xlswrite(filename,Avg,sheet,xlRange); % Writing the excel file
end
This code gives the following output [‍2] :
Fig.1: Values are saved in a single row of excel file
If you want to get the output in a single column then use this xlRange = ['A',num2str(k)]; instead. It'll give you the following output [‍2] :
Fig.2: Values are saved in a single column of excel file
[‍1]: Read the documentation of xlswrite for more details.
[‍2]: Output values may vary since random integers are generated.

Extract same column from multiple excel files using xlsread

I have a directory on C drive containing a number of excel files of the same format. I would like to copy column H from each file into a new file using the following script I found online:
dirs=dir('C:\xxx\*.xlsx');
dircell=struct2cell(dirs);
filenames=dircell(1,:);
range = 'H:H';
n = (numel(filenames));
for i = 1:n;
Newfile(:,i) = xlsread(filenames{i},range);
end
This gives an error message of "Subscripted assignment dimension mismatch." with only one column extracted in the resulting file (Newfile).
I played around with the range and noticed that error occurs when xlsread reaches the end of the list of the first file and stops when the value is empty. My column H's have different number of filled values (i.e. file 1 has 20, file 2 has 100, file 3 has 3, etc.).
So, my question is whether it is possible to modify this script so that when it encounters an empty cell, either an empty cell or a NaN cell is extracted and most importantly that it will move on to the next column.
Thank you so much for your help in advance!
Not having Matlab at home I have to take it from the top of my head.
Since the column you read, H, has different number of valid entries you should not try to force them into the resulting array NewFile directly but rather use a temporary variable
dirs=dir('C:\xxx\*.xlsx');
dircell=struct2cell(dirs);
filenames=dircell(1,:);
range = 'H:H';
n = numel(filenames);
Newfile = NaN*ones(1, n);
for nf = 1:n;
tempVar = xlsread(filenames{nf},range);
r = size(NewFile,1); % get number of rows in NewFile
if length(tempVar) > r
% Make Newfile big enough to fit column nf
Newfile = [Newfile;NaN*ones(length(tempVar)-r,n)];
end
Newfile(:,nf) = tempVar;
end

write information into Excel after each loop

I have a 6x7 matrix(A) and some operation I'm doing on it for k=1:50 (number of loops).
I know that in order to write a single matrix in an excel file I need:
xlswrite('Filename.xls', A, 'A1')
How is it possible to write the information after each loop, in that way that each loop starts at position A1+((k-1)*6+1) in Excel and I have all results of Matrix(A) listed one after each other.
Thank you!
When using the XLSWRITE function, you can avoid having to compute Excel cell ranges each time, by specifying both sheet number and range, where range only gives the first cell to start at.
It is especially useful if the matrix changes size each iteration; we simply take the last cell used and shift it by the number of rows of the matrix.
Example:
offset = 1;
for i=1:5
%# generate different size matrices each loop
A = ones(randi(4),randi(4)).*i;
%# insert matrix in Excel inside the 1st sheet, starting at cell specifed
xlswrite('filename.xls', A, 1, sprintf('A%d',offset));
%# increment offset
offset = offset + size(A,1);
end
this creates an Excel file with the following content:
1 1
1 1
1 1
2 2 2 2
3 3
3 3
4
4
4
4
5 5 5
5 5 5
5 5 5
5 5 5
Note that a connection is made to Excel then closed each time XLSWRITE is called. This has a significant overhead.
A better approach would be to open Excel once, and reuse the same session to write all of your data, then close it once we are done. However, you will have to call the Office Interop functions yourself.
Since the trick I mentioned above won't work now, I will be using the "Calculate Excel Range" function to compute the cell ranges (there are many other implementations of FEX).
Here is the code (reusing some code from a previous answer):
%# output file name
fName = fullfile(pwd, 'file.xls');
%# create Excel COM Server
Excel = actxserver('Excel.Application');
Excel.Visible = true;
%# delete existing file
if exist(fName, 'file'), delete(fName); end
%# create new XLS file
wb = Excel.Workbooks.Add();
wb.Sheets.Item(1).Activate();
%# iterations
offset = 0;
for i=1:50
%# generate different size matrices each loop
A = ones(randi(4),randi(4)).*i;
%# calculate cell range to fit matrix (placed below previous one)
cellRange = xlcalcrange('A1', offset,0, size(A,1),size(A,2));
offset = offset + size(A,1);
%# insert matrix in sheet
Excel.Range(cellRange).Select();
Excel.Selection.Value = num2cell(A);
end
%# save XLS file
wb.SaveAs(fName,1);
wb.Close(false);
%# close Excel
Excel.Quit();
Excel.delete();
In fact, I ran both version with 50 iterations, and compared timings with TIC/TOC:
Elapsed time is 68.965848 seconds. %# calling XLSWRITE
Elapsed time is 2.221729 seconds. %# calling Excel COM directly
I think that xlswrite will overwrite an existing file, so you're better off gathering all the data, then writing it in one go. Also, writing it all in one go will be faster since it involves opening and closing Excel only once.
However, if you really want to write it in a loop, the following should work (assuming you mean going down):
range = sprintf('A%i:G%i', (k-1)*6+[1 6]);
xlswrite('Filename.xls', A, range);
Note that this won't adjust automatically if A changes size.

Convert text to number in Excel in VBA [duplicate]

This question already has answers here:
VBA: Convert Text to Number
(11 answers)
Closed 4 years ago.
For some reason Excel is converting my number into text and adding a preceding apostrophe in every cell in column E3 and F3.
I need to convert columns E3:F3 back to numbers and format them to currency. How do I do that?
A1:K2 is the header.
The code below is not working:
Set wb = objApp.Workbooks.Open("aFile.xls", True, False)
wb.Sheets(1).Rows(2).Delete
wb.Sheets(1).Range("E3:F3") = Mid(wb.Sheets(1).Range("E3:F3"), 2,
Len(wb.Sheets(1).Range("E3:F3")) - 2)
wb.Sheets(1).Range("E3:F3").NumberFormat = "$#,##0.00"
If your text is only a number, the answer is simple. Multiply it by 1.
Say cell A1= '00001234 or a formula or macro returns a piece of text, multiply the answer by 1.
"00001234" * 1 = 1234.
I want to extract the value of a Label or a txtBox on a VBA form.
Num = lblText * 1
Another example:
If .txtLevel10 * 1 > 50 Then...etc.
Also works with some other data types "16-Jan-15" *1 = 16/1/15
Works in Excel & VBA but only if there are no other characters in the original text.
Cheers
Assuming you want the same currency formatting you get from the toolbar, this works:
wb.Sheets(1).Range("E3:F3").Formula = wb.Sheets(1).Range("E3:F3").Value
wb.Sheets(1).Range("E3:F3").Style = "Currency"
Just using worksheet.Range() with no properties forces Excel to guess exactly which property you actually mean (this is called the "default property"), and you get inconsistent results.
Try:
Range("E3:F3").Style = "Currency"
Try highlighting that column and doing Data->Text To Columns (Excel 2003; in 2007+ Text to columns is on one of the ribbons). Click 'Delimited', then 'Next', Next again, then select General as the format. This should convert the whole column into a number.
If this works, it is easily automated. Let me know if you need code.
EDIT - you have to do one column at a time.
Len(wb.Sheets(1).Range("E3:F3"))
For me this just (as expected) throws an error. You'll have to process each cell individually to use your approach.
Dim c as Range
Set wb = objApp.Workbooks.Open("aFile.xls", True, False)
With wb.Sheets(1)
.Rows(2).Delete
For each c in .Range("E3:F3").cells
c.Value = Mid(c.value, 2, Len(c.value)-2)
c.NumberFormat = "$#,##0.00"
next c
End With
This, actually, works. The key is to apply format before setting the value:
Set wb = objApp.Workbooks.Open("aFile.xls", True, False)
wb.Sheets(1).Rows(2).Delete
wb.Sheets(1).Range("E3:F3").NumberFormat = "$#,##0.00"
For Row = 3 To 3 'your rows range in case you need iterate through (1 row only in your case)
For Column = 5 To 6 'E3:F3
wb.Sheets(1).Cells(Row, Column) = Mid(wb.Sheets(1).Cells(Row, Column), 2, Len(wb.Sheets(1).Cells(Row, Column)) - 2)
Next Column
Next Row

Resources