Paste Special Transpose Syntax in Matlab using ActXServer - excel

I am working on a code in Matlab that will open excel spreadsheet, copy a certain range, and paste it in a new sheet transposing my range in the process. I am completely stuck on the PasteSpecial method and cannot figure out how to make it transpose my data. I've tried everything I could think of: tried VBA-like syntax (Transpose=True), tried (Transpose, 1), tried ([],[],[],1), tried obj.Transpose(with all kinds of variations in the brackets)... and all kinds of other stuff to no avail. Please help me if anyone had done this before. Below if my simplified code in case it's needed. Thank you in advance!
Excel = actxGetRunningServer('excel.application');
set(Excel, 'Visible', 1);
Workbooks = Excel.Workbooks;
Workbook = Excel.Workbooks.Open('C:\Users\...test.xlsx');
curr_sheet = get(Workbook,'ActiveSheet');
rngObj = ('A1:C3')
rngObj.Copy
Sheets = Excel.ActiveWorkBook.Sheets;
new_sheet = Sheets.Add;
new_sheet.PasteSpecial; %This is where I am stuck!

The documentation for PasteSpecial has four input arguments to indicate the parameters of the paste operation. As you can see, the fourth option indicates whether to transpose the data or not.
new_sheet.PasteSpecial(NaN, NaN, NaN, true);

Related

Openpyxl - Setting Active Sheet (page.append not working as expected)

I've tried implementing multiple solutions from existing posts, like this one, to no avail:
openpyxl Set Active Sheet
I have a workbook with n number of sheets that I want to iteratively step through, and apply header information to. As far as I can tell, using wb.active = i is setting the active worksheet, but when I follow up with page.append(header), I end up with the header appended n times, ONLY to the index 0 sheet. This is essentially the same q as the link above, but the solution doesn't seem to work.
What am I missing here? I wonder if I need to specify an index for page.append(), but that doesn't seem to be a valid argument for that func.
CODE
header = ['Time [sec]', 'Altitude [km]', 'Velocity [km/s]']
for i in range(len(wb.sheetnames)):
wb.active = i
print(wb.active)
page.append(header)
wb.save(path)
CONSOLE (verifies that the wb.active function is working, but the sheets specified aren't being appended)
<Worksheet "ORB1">
<Worksheet "ORB2">
<Worksheet "ORB3">
<Worksheet "ORB4">
<Worksheet "ORB5">
Here is another version which produces the same result (5x headers applied only to the first sheet).
header = ['Time [sec]', 'Altitude [km]', 'Velocity [km/s]']
for i, s in enumerate(wb.sheetnames):
page.append(header)
wb.save(path)
This one is SOLVED but I want to keep the q up because the solution is... weird.
Earlier in the code I was assigning page = wb.active, and then later using page.append(header).
The issue with that ^, has to do with the format for setting the active sheet.
wb.active is used such that wb.active = sheet_index, rather than the typical function structure where wb.active(sheet_index).
Because of this bizarre arg format, simplifying "wb.active" to "page" breaks this function.
TLDR: This does not work...
page = wb.active
page.append(header)
You must use...
wb.active.append(header)
No idea why that function has such a strange structure, but I suspect I'm not the only person to have had this issue.

excel vba listobject HeaderRowsRange

I am working with list objects in excel and there is one thing that puzzles me:
according to this and many other sites I visited the following line of code is a range:
mytable.headerRowRange("nameofColumn")
mytable being a listobject of a particular sheet.
what I wand to do is hide that column
but this would not work:
mytable.headerRowRange("nameofColumn").EntireColumn.Hidden=True
Why?
the error is: Invalid procedure call or argument.
thanks.
mytable.ListColumns("ID").Range.EntireColumn.Hidden = True
You could also have done
mytable.HeaderRowRange.Find("id").EntireColumn.Hidden = True

Working with Excel sheets in MATLAB

I need to import some Excel files in MATLAB and work on them. My problem is that each Excel file has 15 sheets and I don't know how to "number" each sheet so that I can make a loop or something similar (because I need to find the average on a certain column on each sheet).
I have already tried importing the data and building a loop but MATLAB registers the sheets as chars.
Use xlsinfo to get the sheet names, then use xlsread in a loop.
[status,sheets,xlFormat] = xlsfinfo(filename);
for sheetindex=1:numel(sheets)
[num,txt,raw]=xlsread(filename,sheets{sheetindex});
data{sheetindex}=num; %keep for example the numeric data to process it later outside the loop.
end
I 've just remembered that i posted this question almost 2 years ago, and since I figured it out, I thought that posting the answer could prove useful to someone in the future.
So to recap; I needed to import a single column from 4 excel files, with each file containing 15 worksheets. The columns were of variable lengths. I figured out two ways to do this. The first one is by using the xlsread function with the following syntax.
for count_p = 1:2
a = sprintf('control_group_%d.xls',count_p);
[status,sheets,xlFormat] = xlsfinfo(a);
for sheetindex=1:numel(sheets)
[num,txt,raw]=xlsread(a,sheets{sheetindex},'','basic');
data{sheetindex}=num;
FifthCol{count_p,sheetindex} = (data{sheetindex}(:,5));
end
end
for count_p = 3:4
a = sprintf('exercise_group_%d.xls',(count_p-2));
[status,sheets,xlFormat] = xlsfinfo(a);
for sheetindex=1:numel(sheets)
[num,txt,raw]=xlsread(a,sheets{sheetindex},'','basic');
data{sheetindex}=num;
FifthCol{count_p,sheetindex} = (data{sheetindex}(:,5));
end
end
The files where obviously named control_group_1, control_group_2 etc. I used the 'basic' input in xlsread, because I only needed the raw data from the files, and it proved to be much faster than using the full functionality of the function.
The second way to import the data, and the one that i ended up using, is building your own activeX server and running a single excelapplication on it. Xlsread "opens" and "closes" an activeX server each time it's called so it's rather time consuming (using the 'basic' input does not though). The code i used is the following.
Folder=cd(pwd); %getting the working directory
d = dir('*.xls'); %finding the xls files
N_File=numel(d); % Number of files
hexcel = actxserver ('Excel.Application'); %starting the activeX server
%and running an Excel
%Application on it
hexcel.DisplayAlerts = true;
for index = 1:N_File %Looping through the workbooks(xls files)
Wrkbk = hexcel.Workbooks.Open(fullfile(pwd, d(index).name)); %VBA
%functions
WorkName = Wrkbk.Name; %getting the workbook name %&commands
display(WorkName)
Sheets=Wrkbk.Sheets; %sheets handle
ShCo(index)=Wrkbk.Sheets.Count; %counting them for use in the next loop
for j = 1:ShCo(index) %looping through each sheet
itemm = hexcel.Sheets.Item(sprintf('sheet%d',j)); %VBA commands
itemm.Activate;
robj = itemm.Columns.End(4); %getting the column i needed
numrows = robj.row; %counting to the end of the column
dat_range = ['E1:E' num2str(numrows)]; %data range
rngObj = hexcel.Range(dat_range);
xldat{index, j} = cell2mat(rngObj.Value); %getting the data in a cell
end;
end
%invoke(hexcel);
Quit(hexcel);
delete(hexcel);

How to re-order worksheets using python's xslxwriter

I am using xslxwriter to produce a excel spreadsheet, and I am wondering if there is anyway I can re-order my worksheets in my workbook.
I have tried to change the index, but this doesn't seem to work (index doesn't seem to alter the order).
Any idea if this can be done with xslxwriter, or is there another module I should be using?
I have found a workaround, unfortunately not in the xslxwriter module but the pywin32 addin.
Using the following you can reorder your sheet "WorkSheetToMove" in an Excel spreadsheet:
excel = win32com.client.Dispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Open(Filename="excelyouwanttoreoder.xslx", ReadOnly='False')
for worksheet in wb.Sheets:
if worksheet.Name == "WorkSheetToMove":
worksheet.Move(Before=wb.Sheets("Sheet2"))
wb.Close()

How to add more than 3 sheets to an excel workbook from within MATLAB

How do I add more sheets to an excel workbook from within matlab?
I set up the workbook like so (based on code I got from someone else's post in this forum):
%# create Excel COM Server
Excel = actxserver('Excel.Application');
Excel.Visible = true;
%# create new XLS file
wb = Excel.Workbooks.Add();
wsheet=1;
wb.Sheets.Item(wsheet).Activate();
That's fine. Then later on inside the loop I open a new sheet after so many loops:
...
if loop==sheetlimit,
wsheet=wsheet+1;
wb.Sheets.Item(wsheet).Activate();
end
This works up to sheet 3. But when wsheet=4 I get this error message:
??? Invoke Error, Dispatch Exception: Invalid index.
Error in ==> filename at 97
wb.Sheets.Item(wsheet).Activate();
Appreciate any help. Thanks.
I don't know Matlab but I would be surprised if wb.Sheets.Item(wsheet).Activate(); is actually adding any new worksheets. Most likely it is selecting / activating each worksheet in your wb workbook and your default Excel template has three worksheets. Hence why it errors when it gets to more than three.
Something like this might add a new Excel worksheet:
wb.sheets.Add();
Aargh - comment formatting completely messed up - I'll re-enter it as an new answer
Yes wb.sheets.Add(); will work. You can query the available methods of an interface like this:
methods(wb.sheets)
which gives:
Methods for class Interface.000208D7_0000_0000_C000_000000000046:
Add FillAcrossSheets PrintOut addproperty events loadobj set
Copy Item PrintPreview delete get release
Delete Move Select deleteproperty invoke saveobj

Resources