如何使用xlswrite为从MATLAB写入到Excel的矩阵指定名称?
这相当于打开xls工作表,选择数据并右击->定义名称。在这里,我可以给矩阵分配一个字符串。我怎么能用MATLAB做这件事?
我使用的另一个应用程序根据命名范围从xls文件中读取数据。
发布于 2015-04-19 10:51:53
据我所知,您不能在函数xlswrite
中这样做。您必须在Matlab中使用excel COM服务器。
下面的示例来自Mathworks示例,但适合您的需要。请注意,您不需要以这种方式使用xlswrite
,而是直接将数据输入excel表。
%// First, open an Excel Server.
e = actxserver('Excel.Application');
%// Insert a new workbook.
eWorkbook = e.Workbooks.Add;
e.Visible = 1;
%// Make the first sheet active.
eSheets = e.ActiveWorkbook.Sheets;
eSheet1 = eSheets.get('Item', 1);
eSheet1.Activate;
%// Name the range you want:
e.Names.Add( 'TestRange' , '=Sheet1!$A$1:$B$2' ) ;
%// since you are here, directly put the MATLAB array into the range.
A = [1 2; 3 4];
eActivesheetRange = e.Activesheet.get('Range', 'TestRange');
eActivesheetRange.Value = A ;
%// Now, save the workbook.
eWorkbook.SaveAs('myfile.xls');
编辑以在评论中回答您的问题:
如果要以编程方式定义范围地址,则必须将地址构建为字符串。行索引非常简单,但是activeX中的excel AAA...
不允许逐个索引引用单元格/列/范围,因此需要进行更多的修改以使列的地址正确(以防AAA...
范围溢出)。
下面的部分应该允许您这样做:
%// test data
A = rand(4,32);
%// input the upper left start of the range you want
sheetName = 'Sheet1' ;
startCol = 'Y' ;
startRow = 4 ;
%// calculate the end coordinates of the range
endRow = startRow + size(A,1)-1 ;
%// a bit more fiddling for the columns, as they could have many "characters"
cols = double(startCol)-64 ;
colIndex = sum(cols .* 26.^(length(cols)-1:-1:0)) ; %// index of starting column
endCol = eSheet1.Columns.Item(colIndex+size(A,2)-1).Address ;
endCol = endCol(2:strfind(endCol, ':')-1) ; %// column string reference
%// build range string in excel style
rngString = sprintf('=%s!$%s$%d:$%s$%d',sheetName,startCol,startRow,endCol,endRow) ;
myRange = eSheet1.Range(rngString) ; %// reference a range object
myRange.Value = A ; %// assign your values
%// Add the named range
e.Names.Add( 'TestRange' , myRange ) ;
测试数据故意从列Y
溢出到列BD
,以确保地址转换能够处理(i)添加字符和(ii)从Ax
到By
的溢出。这似乎很好,但是如果数据数组不是那么宽,那么您就不需要担心它了。
https://stackoverflow.com/questions/29733977
复制相似问题