How to save an Excel sheet as PDF through MATLAB? - excel

I am using the following code:
hExcel = actxserver('Excel.Application');
hWorkbook = hExcel.Workbooks.Open(sprintf('%s','C:\test.xlsx'));
hWorksheet = hWorkbook.Sheets.Item(1);
hRange = hWorksheet.Range('A1:O10');
hRange.ExportAsFixedFormat('xlTypePDF','test_out.pdf');
The Excel ActiveX server allows me to do the usual stuff, but the last line doesn't do anything. Neither does it throw any error.
Does anyone know how to do this?

I think you need to use hWorkbook.ExportAsFixedFormat, not hRange.ExportAsFixedFormat.
Also, you'll need to specify the full path to the output file as C:\test_out.pdf.

Related

MATLAB: How to paste fig Into excel, then save and close excel file?

I generated an excel file in MATLAB and successfully saved and closed it using this:
invoke(Workbook,'Save')
invoke(Excel,'Quit');
delete(Excel);
clear Excel;
But then when I add a figure to that excel file using PlotInExcel, I can't save and close the file using that same code again. Here is PlotInExcel:
function PlotInExcel
x= {1:10};
a= cell2mat(x);
y= {1:10};
b= cell2mat(y);
%............plotting......................
plot(a,b);
xlabel('X Values');
ylabel('Y Values');
print -dmeta; %.................Copying to clipboard
FILE = 'C:DATA.xlsx';
Range='OL14';
%.............excel COM object...........................................
Excel = actxserver ('Excel.Application');
Excel.Visible = 1;
if ~exist(FILE,'file')
ExcelWorkbook=Excel.Workbooks.Add;
ExcelWorkbook.SaveAs(FILE);
ExcelWorkbook.Close(false);
end
invoke(Excel.Workbooks,'Open',FILE); %Open the file
ActiveSheet = Excel.ActiveSheet;
ActiveSheetRange = get(ActiveSheet,'Range',Range);
ActiveSheetRange.Select;
ActiveSheetRange.PasteSpecial; %.................Pasting the figure to the selected location
%-----------------------------------end of function"PlotInExcel----------
How do I get MatLab to save this file now and exit? The aforementioned code at top doesn't work now. Is there someway to add code to the function? or can/should I Save/Close the file outside the function back in my script?
With enough bashing around, I was finally able to answer my own question. I'm posting the resolution here in the event anyone else has this problem. I removed the lines at the beginning because they just produced a test figure. The function below assumes you have your own figure you want to paste into an excel spreadsheet. BTW, you must have your figure saved to the clipboard before running this function.
function PlotInExcel
FILE = 'C:\DATA.xlsx'; %identify the name and location of your excel spreadsheet
Range='R1'; %select where you want your figure pasted in the speadsheet (cell ID)
%.............excel COM object............................................................................
Excel = actxserver ('Excel.Application');
Excel.Visible = 1;
if ~exist(FILE,'file')
ExcelWorkbook=Excel.Workbooks.Add;
ExcelWorkbook.SaveAs(FILE);
ExcelWorkbook.Close(false);
end
invoke(Excel.Workbooks,'Open',FILE); %Open the file
ActiveSheet = Excel.ActiveSheet;
ActiveSheetRange = get(ActiveSheet,'Range',Range);
ActiveSheetRange.Select;
ActiveSheetRange.PasteSpecial; %.................Pasting the figure to the selected location
Excel.ActiveWorkbook.Save % Now save the workbook
if eq(Excel.ActiveWorkbook.Saved,1)
Excel.ActiveWorkbook.Close;
else
Excel.ActiveWorkbook.Save;
end
invoke(Excel, 'Quit'); % Quit Excel
delete(Excel); % End process
end

Error accessing Names in Excel using Interop

I am programming an application in C# (Visual Studio 2015) and I need to update an .xlsm file.
This file has many formulas, over 1200 names and vba code.
I am using the Interop library and I am able to update some cells and get the relative updated formulas but i have some problem with the Names defined in the Excel.
The program recognizes the names in the Names collection but doesnt let me access some of the names.
When I try to access the value of the cell using its name it produces an exception.
I dont understand why i can access some of the names and others no.
Besides, in the excel, I can see the Name in the combo but when I select it, the cursor doesn't position over the cell.
In my program I could avoid this problem accessing the cells using the reference instead of the Name, but the vba in the excel uses the names and if i open the file from my app it doesnt work.
I am using this code:
excelApplication = new Microsoft.Office.Interop.Excel.Application();
excelApplication.ScreenUpdating = true;
excelApplication.Visible = true;
excelApplication.DisplayAlerts = false;
excelWorkbook = excelApplication.Workbooks.Open(txtFicheroEntrada.Text);
wsDatos = excelWorkbook.Worksheets[1];
wsDatos.Select();
foreach(Microsoft.Office.Interop.Excel.Name v in excelWorkbook.Names)
{
string NombreVar = v.Name;
//here i found the name BobinadoAT correctly. It exists
if (NombreVar == "BobinadoAT" ){ Console.WriteLine(NombreVar); }
}
if (wsDatos.Range["BobinadoAT"] != null) //but here this produces an exception
{
string valorcelda = wsDatos.Range["BobinadoAT"].Value.ToString();
}
¿does anyone work with many excel Names?
¿Am I accessing the names incorrectly?

Can't call method "worksheet" on an undefined value

I have a problem parsing excel file in the same perl code:
I get this error:
"Can't call method "worksheet" on an undefined value at
./parse_pathsim_results.pl line 223"
Interestingly in the perl code I have if I parse another file (delay xls) before the intended slope xls file it works.
Here is the code:
use Spreadsheet::ParseExcel::SaveParser;
$input_delay_csv_file = "./presto/prs/c2x_delay.xls";
$input_slope_excel_file = "./presto/prs/c2x_slope.xls";
$slope_parser = Spreadsheet::ParseExcel::SaveParser->new();
$delay_parser = Spreadsheet::ParseExcel::SaveParser->new();
The code works if I use the following two lines, but I don't want to.
$workbook = $delay_parser->Parse("$input_delay_csv_file");
$worksheet = $workbook->worksheet("Sheet1");
This is where it creates a problem if the above two lines are commented.
$new_workbook = $slope_parser->Parse("$input_slope_excel_file");
$worksheet = $new_workbook->worksheet("Sheet1");
Without you giving much information and only snippets of your code it is hard to say.
The great suspect is the file format itself, as the Parse method does not return a $workbook, the parser returned undef
I recently had a problem like this where the excel file was a quite recent format version. (ending on .xlsx and not .xls) Opening the file with MS Excel and saving as an older excel format did the trick.
Your first file looks as if it was a plain CSV file, and therefore had no problem parsing.

How to read a specific range of several excel files in MATLAB

I want to write a program that is able to read a specific range of numerous excel files in a folder.
because I need MATLAB to read from several excel files, I can't use a coding like this :
xlsread('Report1',1,'k41')
Is it possible to modify below codes in a way to be able to read 'K41' cellular from each excel file?
clc
clear all
Folder = 'D:\Program Files\MATLAB\R2013a\bin';
XLfiles = dir(fullfile(Folder, '*.xlsx'));
for i = 1:length(XLfiles)
data = xlsread(fullfile(Folder, XLfiles(i).name));
end
As excaza said, xlsread should work, just check the 'range' parameter from xlsread, needs to be a string in this format (this is to import only C1).
'C1:C2'
If you use K41:K41 it imports nothing, as it is a 0 range. Maybe that is the confusion here.
See if this might work
all_cells = []; %store all your cells in here
Folder = 'D:\Program Files\MATLAB\R2013a\bin';
XLfiles = dir(fullfile(Folder, '*.xlsx'));
for i = 1:length(XLfiles)
all_cells (end+1)= xlsread(fullfile(Folder, XLfiles(i).name), 'K41:K42');
end

Add sparklines to excel with matlab

With MATLAB I can start a COM server and programmatically write to an Excel workbook. However, I can't figure out a way to add sparklines (suggestions appreaciated):
% Open new workbook
excel = actxserver('excel.application');
excel.visible = 1;
wrkbook = excel.Workbooks.Add();
sheet = wrkbook.Sheets.Item(1);
% Write some data
sheet.Range('B1:Z1').Value = rand(1,25);
Here is the problem:
% Add column sparklines to 'A1', type 'xlSparkColumn' and DataSource: 'B1:Z1'
sheet.Range('A1').SparklineGroups.Add('xlSparkColumn','B1:Z1')
I get the following error:
Error using Interface.Microsoft_Excel_15.0_Object_Library.SparklineGroups/Add
Error: Object returned error code: 0x800A03EC
Close/cleanup
% Close without saving
wrkbook.Saved = 1;
wrkbook.Close
excel.Quit
delete(excel)
Reference to SparklineGroup Object (Excel). I am on win7 64bit, R2013a and Excel 2013.
Try:
xlSparkColumn = 2;
sheet.Range('A1').SparklineGroups.Add(xlSparkColumn,'B1:Z1')
In the future, if you want to figure out the corresponding value for a certain constant/enum, use the IL DASM tool as shown in these posts.
EDIT
Ok it turns out that the enumeration xlSparkColumn was not the real issue here, you could either specify it as a string argument or pass the underlying integer value for the enum.
The problem as you mentioned in the comments is that you had the R1C1 reference style set instead of the default A1 reference style, thus the range specified in your call was not valid in that format.
Either of these will work:
excel.ReferenceStyle = 'xlR1C1';
sheet.Range('A1').SparklineGroups.Add('xlSparkColumn','R1C2:R1C26')
excel.ReferenceStyle = 'xlA1';
sheet.Range('A2').SparklineGroups.Add('xlSparkColumn','B1:Z1')

Resources