本段程序的主要功能是:按行或者按列依次循环往表格里写数据。
1 function main() 2 clc; 3 close all; 4 clear; 5 6 year=2017;month=12; 7 daynum=eomday(year,month); 8 % date=201712; 9 % daynum=cal_day(date); 10 11 file_test = [pwd '\test_harder.xls']; 12 try 13 Excel = actxGetRunningServer('Excel.Application'); 14 catch 15 Excel = actxserver('Excel.Application'); 16 end; 17 18 % Excel.Visible = 1; % set(Excel, 'Visible', 1); 19 20 if exist(file_test,'file'); 21 Workbook = Excel.Workbooks.Open(file_test); 22 else 23 Workbook = Excel.Workbooks.Add; 24 Workbook.SaveAs(file_test); 25 end 26 27 Sheets = Excel.ActiveWorkbook.Sheets; % Sheets = Workbook.Sheets; 28 Sheet1 = Sheets.Item(1); 29 Sheet1.Activate; 30 31 % 第一行,车号,车厢号,日期 32 Sheet1.Range('A1').Value ='车号'; 33 Sheet1.Range('B1').Value='车厢号'; 34 % xlswrite(file_test,{'车号'},'Sheet1','A1'); 35 % xlswrite(file_test,{'车厢号'},'Sheet1','B1'); 36 37 for i=1:daynum 38 a=date2str(year,month,i); 39 if i+2<27 40 Bs=[char(66+i) num2str(1)] 41 else 42 Bs=[char(65) char(40+i) num2str(1)] 43 44 end 45 Sheet1.Range(Bs).ColumnWidth = 13; 46 Sheet1.Range(Bs).HorizontalAlignment = 3; 47 Sheet1.Range(Bs).Value =a; 48 end 49 50 %第一列,共18辆车,每辆车8个车厢,即每8个单元格合并成一列车 51 train_total=18; 52 carriage_total=8; 53 54 55 for i=1:train_total 56 start_str=['A' num2str((i-1)*8+2)] 57 As=['A' num2str((i-1)*8+2) ':A' num2str(i*8+1)] 58 Sheet1.Range(As).MergeCells = 1; 59 Sheet1.Range(start_str).VerticalAlignment = 2; 60 Sheet1.Range(start_str).HorizontalAlignment = 3; 61 if i<6 62 train_num=num2str(2000+i); 63 else 64 if i<11 65 train_num=num2str(2000+i+5); 66 else 67 train_num=num2str(2000+i+10); 68 end 69 end 70 Sheet1.Range(start_str).Value =train_num; 71 % xlswrite(file_test,train_num,'Sheet1',start_str); 72 for j=1:carriage_total 73 Bs=['B' num2str((i-1)*8+1+j)] 74 carriage_num=num2str(j) 75 Sheet1.Range(Bs).Value =carriage_num; 76 % xlswrite(file_test,carriage_num,'Sheet1',Bs); 77 end 78 end 79 80 Workbook.Save; 81 82 83 function [str_cell_date]=date2str(year,month,day) 84 y=num2str(year); 85 m=num2str(month); 86 d=num2str(day); 87 str_cell_date=strcat(y,'/',m,'/',d);
ps:
1.Sheet1.Range(start_str).Value =train_num;这种格式,仅仅是对某个表格赋值,但是并没有写入到表格中,最后加上‘Workbook.Save;’才能把每个表格的value保存到sheet中。
2. 我最开始试着xlswrite(file_test,carriage_num,'Sheet1',Bs);直接往表格里写内容,但是,经常出现‘The file .xlsx is not writable. It may be locked by another process.’最终也没有找到原因和解决方法,如果有谁知道,麻烦留言。感觉.Value的赋值语句和xlswrite语句一块用,就会比较容易出错误
3.这段程序最主要的功能是实现了表格的循环,start_str=['A' num2str((i-1)*8+2)] Bs=[char(66+i) num2str(1)],A,B,C等,可以用char(ASCII码)表示,[ 字母 数据 ]可以用来表示表格的行列号。