Part 1ArticleThis article continues with this type. It briefly introduces how to import the data in the list to an Excel file.
DetailsCodeAs follows:
Because it is an Excel file, you need to use office-related DLL, so add the reference of the corresponding DLL, and thenProgramAdd the following namespace:
UsingMicrosoft. Office. InterOP. Excel;
Student class:
Public Class Student { Private String ID; Public String Id {Get { Return ID ;} Set {Id = Value ;}} Private String Name; Public String Name { Get { Return Name ;} Set {Name = Value ;}} Private String Age; Public String Age { Get { Return Age ;} Set {Age = Value ;}}}
Generate simple analog data:
Private List <student> Getstudentdata () {list <Student> studentlist = New List <student>(); Student S1 = New Student (); s1.id = " 1 " ; S1.name = " Haha " ; S1.age = " 10 " ; Student S2 =New Student (); s2.id = " 2 " ; S2.name = " Xixi " ; S2.age = " 20 " ; Student S3 = New Student (); s3.id = " 3 " ; S3.name = " Lolo " ; S3.age = " 30 " ; Studentlist. Add (S1); studentlist. Add (S2); studentlist. Add (S3 ); Return Studentlist ;}
Use reflection to obtain all attributes of the type (so that the title of all columns can be generated later ):
private propertyinfo [] getpropertyinfoarray () {propertyinfo [] props = null ; try {type = typeof (ericsunapp. student); Object OBJ = activator. createinstance (type); props = type. getproperties (bindingflags. public | bindingflags. instance) ;} catch (exception ex) {} return props ;}
Traverse the list and save the data as an Excel file:
Private Void Savedatatoexcelfile (list <student> studentlist, String Filepath ){ Object Misvalue = System. reflection. Missing. value; application xlapp = New Application (); workbook xlworkbook = Xlapp. workbooks. Add (misvalue); worksheet xlworksheet = (Worksheet) xlworkbook. worksheets. get_item ( 1 ); Propertyinfo [] props = Getpropertyinfoarray (); For ( Int I = 0 ; I <props. length; I ++ ) {Xlworksheet. cells [ 1 , I + 1 ] = Props [I]. Name; // Write the column name } For (Int I = 0 ; I <studentlist. Count; I ++ ) {Xlworksheet. cells [I + 2 , 1 ] = Studentlist [I]. ID; xlworksheet. cells [I + 2 , 2 ] = Studentlist [I]. Name; xlworksheet. cells [I + 2 , 3 ] =Studentlist [I]. Age ;} Try {Xlworkbook. saveas (filepath, xlfileformat. xlworkbooknormal, misvalue, xlsaveasaccessmode. xlexclusive, misvalue); xlworkbook. Close ( True , Misvalue, misvalue); xlapp. Quit ();} Catch (Exception ex ){}}
.......