Use Response to export Excel and response to export excel
We have seen the following types of export Excel tables:
1. NPIO method, high-imitation Java. Powerful, but heavy.
2. encapsulated by the predecessors ....
3. What I want to talk about in this article ..
I want to export an Excel table again this Friday. It is estimated that the export of the platform encapsulation is heavy. I want to use response to export an excel table, which is a word and never used. I went to Baidu University ~
/// <Summary> /// obtain The table header /// </summary> /// <param name = "caption"> The caption. </param> /// <returns> System. string. </returns> // <remarks> Editor: v-liuhch CreateTime: 19:44:44 </remarks> private string GetHeaderName (string caption) {string headName = string. empty; switch (caption) {case "SerialNo": headName = "SN code"; break; case "PrizeName": headName = "prize name"; break; case "TelPhone ": headName = "receiving phone number"; break; case "NickName": headName = "name"; break; case "AwardingTime": headName = "receiving time"; break; case "OkPrizeTime": headName = "pumping time"; break; default: headName = ""; break;} return headName ;}
The above section obtains the column title.
Next is the export process:
Private void ExportSN (HttpContext context) {string accode = context. request. queryString ["accode"]; HttpResponse response = context. response; string fileName = "SN code export table-" + DateTime. now. tow.datestring (); excelHeader = string. empty; excelContent = string. empty; DataTable dt = PrizeAdapter. instance. snManagerData (accode); // obtain the data source DataRow [] dr = dt. select (); int colCount = dt. columns. count; string headName = string. empty; // The row title for (int I = 0; I <colCount; I ++) {headName = GetHeaderName (dt. columns [I]. caption); if (I = colCount-1) {excelHeader + = headName + "\ n";} else {excelHeader + = headName + "\ t ";}} // row data foreach (DataRow row in dt. rows) {for (int I = 0; I <colCount; I ++) {if (I = colCount-1) {excelContent + = row [I]. toString () + "\ n";} else {excelContent + = row [I]. toString () + "\ t" ;}}// ExportGotPrizeSn (context); response. contentEncoding = System. text. encoding. getEncoding ("GB2312"); response. contentType = "application/vnd. ms-excel "; response. appendHeader ("Content-Disposition", "attachment; filename=test.xls"); response. write (excelHeader); response. write (excelContent); response. flush (); response. end ();}
Pay attention to the specified contenttype.
However, there is always a legacy problem:
When you open an exported Excel table, the following prompt is displayed:
Some people say that there is still a problem with code writing, and some say that there is a problem with Office ....
Beg to pass ~~~~~~ ··