ASP. net mvc exports IList & lt; T & gt; to the generic class of the Excel document (inherited from ActionRe

Source: Internet
Author: User

 

Recently, I used the Excel export function in the MVC project. I found some materials on the Internet and wrote a general generic class (ExcelResult ). Because it is directly inherited from the ActionResult abstract class, it is very convenient to use. In the Action of the controller, it can be directly instantiated and returned. I am not very familiar with the code, and the code I write is a little bad. I hope you can correct it.

 

To put it bluntly, directly use the complete code:

View Code

1 /// <summary>

2 // provides the ability to export generic set data to an Excel file.

3 /// </summary>

4 /// <typeparam name = "T"> </typeparam>

5 public class ExcelResult <T>: ActionResult where T: new ()

6 {

7 public ExcelResult (IList <T> entity, string fileName)

8 {

9 this. Entity = entity;

10 this. FileName = fileName;

11}

12

13 public ExcelResult (IList <T> entity)

14 {

15 this. Entity = entity;

16

17 DateTime time = DateTime. Now;

18 this. FileName = string. Format ("{0 }_{ 1 }_{ 2 }_{ 3 }",

19 time. Month, time. Day, time. Hour, time. Minute );

20}

21

22 public IList <T> Entity

23 {

24 get;

25 set;

26}

27

28 public string FileName

29 {

30 get;

31 set;

32}

33

34 public override void ExecuteResult (ControllerContext context)

35 {

36 if (Entity = null)

37 {

38 new EmptyResult (). ExecuteResult (context );

39 return;

40}

41

42 SetResponse (context );

43}

44

45 /// <summary>

46 // configure and send a request response to the client.

47 /// </summary>

48 /// <param name = "context"> </param>

49 private void SetResponse (ControllerContext context)

50 {

51 StringBuilder sBuilder = ConvertEntity ();

52 byte [] bytestr = Encoding. Unicode. GetBytes (sBuilder. ToString ());

53

54 context. HttpContext. Response. Clear ();

55 context. HttpContext. Response. ClearContent ();

56 context. HttpContext. Response. Buffer = true;

57 context. HttpContext. Response. Charset = "GB2312 ";

58 context. HttpContext. Response. ContentEncoding = System. Text. Encoding. UTF8;

59 context. HttpContext. Response. ContentType = "application/ms-excel ";

60 context. HttpContext. Response. AddHeader ("Content-Disposition", "attachment; filename =" + FileName + ". xls ");

61 context. HttpContext. Response. AddHeader ("Content-Length", bytestr. Length. ToString ());

62 context. HttpContext. Response. Write (sBuilder );

63 context. HttpContext. Response. End ();

64}

65

66 // <summary>

67 // convert a generic set into a string that combines an Excel table.

68 /// </summary>

69 /// <returns> </returns>

70 private StringBuilder ConvertEntity ()

71 {

72 StringBuilder sb = new StringBuilder ();

73

74 AddTableHead (sb );

75 AddTableBody (sb );

76

77 return sb;

78}

79

80 /// <summary>

81 // combine the Excel table based on the attribute values of each item in the IList generic set.

82 /// </summary>

83 /// <param name = "sb"> </param>

84 private void AddTableBody (StringBuilder sb)

85 {

86 if (Entity = null | Entity. Count <= 0)

87 {

88 return;

89}

90

91 PropertyDescriptorCollection properties = FindProperties ();

92

93 if (properties. Count <= 0)

94 {

95 return;

96}

97

98 for (int I = 0; I <Entity. Count; I ++)

99 {

100 for (int j = 0; j <properties. Count; j ++)

101 {

102 string sign = j = properties. Count-1? "\ N": "\ t ";

103 object obj = properties [j]. GetValue (Entity [I]);

104 obj = null? String. Empty: obj. ToString ();

105 sb. Append (obj + sign );

106}

107}

108}

109

110 /// <summary>

111 // combine the Excel header based on all attribute names of the specified type T.

112 /// </summary>

113 /// <param name = "sb"> </param>

114 private void AddTableHead (StringBuilder sb)

115 {

116 PropertyDescriptorCollection properties = FindProperties ();

117

118 if (properties. Count <= 0)

119 {

120 return;

121}

122

123 for (int I = 0; I <properties. Count; I ++)

124 {

125 string sign = I = properties. Count-1? "\ N": "\ t ";

126 sb. Append (properties [I]. Name + sign );

127}

128}

129

130 /// <summary>

131 // return the attribute set of the specified type T.

132 /// </summary>

133 /// <returns> </returns>

134 private static PropertyDescriptorCollection FindProperties ()

135 {

136 return TypeDescriptor. GetProperties (typeof (T ));

137}

138}

 

Call the method in the controller:

1 public ActionResult Index ()

2 {

3 List <Product> products = new List <Product> ();

4 for (int I = 0; I <100; I ++)

5 {

6 products. Add (new Product ()

7 {

8 ID = "000001 ",

9 Name = "test ",

10 Description = "test"

11 });

12}

13 return new ExcelResult <Product> (products );

14}

 

The Product class definition used in the code above:

1 public class Product

2 {

3 public Product ()

4 {

5

6}

7

8 public string ID {get; set ;}

9 public string Name {get; set ;}

10 public string Description {get; set ;}

11}

 

Excel file exported from results:

 

 

From: iJerome

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.