Matlab 操作 Excel 复制 Sheet、添加单元格批注 您所在的位置:网站首页 将工作表sheet1的内容复制到sheet2 Matlab 操作 Excel 复制 Sheet、添加单元格批注

Matlab 操作 Excel 复制 Sheet、添加单元格批注

2023-12-21 00:24| 来源: 网络整理| 查看: 265

以前只知道 Matlab 可以写 Excel,但是一直没有涉及到复制 Sheet、添加单元格批注这些功能代码。

后来查资料发现,Matlab 自身是没有这一块功能的,但是可以调用 COM 服务器,通过它去实现更丰富的 Excel 操作。下面简单演示一下如何实现。

场景假设

假设现在有这么一个场景,我手上有一个 5×5 的单位矩阵,希望对该数据做如下操作:

把他写入到 Excel 中的 Sheet1 上 复制一份到 Sheet2 上,并将 Sheet2 重命名为 “CopyFromSheet1” 在 Sheet2 上将对角元素的单元格全部添加批注 “这是对角元素” COM 服务器

COM 服务器。可以简单理解一个封装好了的能够调用 Excel 操作的接口。介绍一些即将用到的功能:

开启 Excel 的 COM 服务器:

e = actxserver('Excel.Application');

打开一份Excel表,也称工作簿(Workbook)。

ewb = e.Workbooks.Open(excel_name);

⚠注意

excel_name 必须为绝对路径!!!!

选择一个Sheet:

% 方法1 sheet1 = ewb.Worksheets.Item(1); % 方法2 sheet1 = ewb.Worksheets.Item('Sheet1');

Sheet重命名:

ewb.Worksheets.Item(1).Name = 'Sheet1';

复制Sheet到其后:

sheet1.Copy(sheet1);

选择单元格:

temp_cell = sheet2.Range(cell_name);

单元格批注清除与添加:

temp_cell.ClearComments(); % 清空批注 temp_cell.AddComment('这是对角元素'); % 添加批注 代码实现 clear;close all;clc; %% 数据写入 excel data = eye(5,5); fullpath = pwd; % 当前文件路径 excel_name = [fullpath,'\','data.xls']; xlswrite(excel_name, data, 'Sheet1'); %% 激活 actxserver try e = actxGetRunningServer('Excel.Application'); % 检查当前是否开启了excel服务器 catch e = actxserver('Excel.Application'); % 未检测到则手动开启excel服务器 end %% 对 excel 进行操作 ewb = e.Workbooks.Open(excel_name); % 复制一份sheet1,并重命名 sheet1 = ewb.Worksheets.Item(1); % 选择sheet1 % sheet1 = ewb.Worksheets.Item('Sheet1'); % 选择sheet1 sheet1.Copy(sheet1); % sheet1后面复制一份sheet2 ewb.Worksheets.Item(2).Name = 'CopyFromSheet1'; ewb.Worksheets.Item(1).Name = 'Sheet1'; % sheet2中对角元素单元格添加批注“对角元素” sheet2 = ewb.Worksheets.Item(2); for i = 1:5 cell_name = sprintf('%s%d',char(64+i),i); temp_cell = sheet2.Range(cell_name); % 定位单元格 temp_cell.ClearComments(); % 清空批注 temp_cell.AddComment('这是对角元素'); % 添加批注 end ewb.Save; % 保存工作簿 ewb.Close(false); % 关闭工作簿 e.Quit; % 退出工作簿 e.delete; % 删除对象 测试与验证

image

image

参考资料 创建 COM 服务器 - MATLAB actxserver - MathWorks 中国 Copy an Excel worksheet from one workbook to another with Matlab How to write xls comment nodes (red corners) from Matlab ? Changing the name of the sheet in excel 知乎 | Excel和Matlab的亲密交互 matlab excel的sheet增加,重命名操作


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有