默认情况下,xlsread 将日期/时间字段检索为根据当前系统区域设置格式化的字符串。问题是在大多数情况下,秒的小数部分不会显示,当您导入文件时会丢失。在the documentation of xlsread 的末尾有一个注释解释了这一点:
xlsread 将格式化的日期导入为字符串(例如“10/31/96”),basic 模式和没有 Excel for Windows 的计算机上除外。
Fortunately,您可以在xlsread 中传递custom processing function 以获取未格式化的原始值(这仅在安装了Excel 软件的Windows 计算机上支持)。正如@RonRosenfeld 在 cmets 中解释的那样,Excel 将日期时间存储为 serial numbers,表示自 1900 年 1 月 00 日以来的小数天数:
Excel 将日期存储为连续的序列号,以便在计算中使用它们。默认情况下,1900 年 1 月 1 日是序列号 1,而 2008 年 1 月 1 日是序列号 39448,因为它是 1900 年 1 月 1 日之后的 39,448 天。
您可以使用.Value2 属性从 COM/ActiveX 获取未格式化的值。
请注意,MATLAB 有自己的存储 serial date numbers 的约定(作为自 00-January-0000 以来的小数天数)。因此,一旦我们从 Excel 加载原始序列号,我们需要将其转换为 MATLAB 使用的约定。使用 MATLAB 中的 datetime 类,转换很容易,如 here 所示。
现在我们已经解决了所有问题,下面是加载具有完整日期/时间精度的 Excel 文件的代码:
function t = loadMyExcelFile(fnameXLSX, sheet)
% read Excel sheet using our custom processing function to get the
% raw dates without any formatting
if nargin<2, sheet = 1; end
[~,~,~,custom] = xlsread(fnameXLSX, sheet, '', '', @CustomProcessFcn);
% convert excel dates to MATLAB datetime, also customize how
% the datetime values are displayed (with full precision)
dt = datetime(cell2mat(custom(:,1)), 'ConvertFrom','excel', ...
'Format','yyyy-MM-dd HH:mm:ss.SSSSSS');
val = cell2mat(custom(:,2));
% compute the milliseconds part alone
ms = round(rem(dt.Second, 1) * 1000);
% build and return results as a MATLAB table
t = table(dt, val, ms);
end
function [data, V2] = CustomProcessFcn(data)
V2 = data.Value2;
end
为了验证上述导入功能,我创建了一个带有随机日期和值的 Excel 表格示例(如果您想继续,可以download it here)。
(注意:我将日期的单元格格式更改为自定义yyyy-mm-dd hh:mm:ss.000 以查看毫秒部分)。
最后,您可以加载数据并随心所欲地对其进行操作:
>> t = loadMyExcelFile('Book1.xlsx')
t =
dt val ms
__________________________ _______ ___
2016-03-28 23:00:25.100877 0.31472 101
2016-03-29 18:58:28.578988 0.72052 579
2016-03-30 10:19:04.318113 0.3475 318
2016-03-31 10:00:26.065898 0.76088 66
2016-04-01 14:19:13.908256 0.89324 908
2016-04-02 04:29:42.858488 0.49078 858
2016-04-03 07:12:32.249770 0.26928 250
2016-04-04 16:48:25.073809 0.31616 74
2016-04-05 08:51:05.228647 0.77366 229
2016-04-06 21:38:29.768989 1.2386 769
2016-04-07 06:55:49.555229 0.89617 555
2016-04-08 01:13:40.028169 1.3668 28
2016-04-09 23:38:56.049314 1.8239 49
2016-04-10 04:13:09.258885 1.8093 259
2016-04-11 09:40:38.799400 2.1096 799
2016-04-12 03:37:27.442933 1.7515 443
2016-04-13 12:20:01.502968 1.6732 503
2016-04-14 18:15:25.406924 2.089 407
2016-04-15 14:46:10.802325 2.3812 802
2016-04-16 02:58:43.615177 2.8407 615
>> plot(t.dt, t.val)