ASP.NET导入EXCEL方法汇总

时间:2023-03-10 03:34:56
ASP.NET导入EXCEL方法汇总
  1. 1、由dataset生成
  2. public void CreateExcel(DataSet ds,string typeid,string FileName)
  3. {
  4. HttpResponse resp;
  5. resp = Page.Response;
  6. resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  7. resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
  8. string colHeaders= "", ls_item="";
  9. int i=0;
  10. //定义表对象与行对像,同时用DataSet对其值进行初始化
  11. DataTable dt=ds.Tables[0];
  12. DataRow[] myRow=dt.Select("");
  13. // typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件
  14. if(typeid=="1")
  15. {
  16. //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
  17. for(i=0;i     colHeaders+=dt.Columns[i].Caption.ToString()+"\t";
  18. colHeaders +=dt.Columns[i].Caption.ToString() +"\n";
  19. //向HTTP输出流中写入取得的数据信息
  20. resp.Write(colHeaders);
  21. //逐行处理数据
  22. foreach(DataRow row in myRow)
  23. {
  24. //在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
  25. for(i=0;i      ls_item +=row[i].ToString() + "\t";
  26. ls_item += row[i].ToString() +"\n";
  27. //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
  28. resp.Write(ls_item);
  29. ls_item="";
  30. }
  31. }
  32. else
  33. {
  34. if(typeid=="2")
  35. {
  36. //从DataSet中直接导出XML数据并且写到HTTP输出流中
  37. resp.Write(ds.GetXml());
  38. }
  39. }
  40. //写缓冲区中的数据到HTTP头文件中
  41. resp.End();
  42. }
  43. 2、由datagrid生成
  44. public void ToExcel(System.Web.UI.Control ctl)
  45. {
  46. HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
  47. HttpContext.Current.Response.Charset ="UTF-8";
  48. HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
  49. HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.msexcel/
  50. msword
  51. ctl.Page.EnableViewState =false;
  52. System.IO.StringWriter tw = new System.IO.StringWriter() ;
  53. System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
  54. ctl.RenderControl(hw);
  55. HttpContext.Current.Response.Write(tw.ToString());
  56. HttpContext.Current.Response.End();
  57. }
  58. 用法:ToExcel(datagrid1);
  59. 3、这个用dataview
  60. public void OutputExcel(DataView dv,string str)
  61. {
  62. //
  63. // TODO: 在此处添加构造函数逻辑
  64. //
  65. //dv为要输出到Excel的数据,str为标题名称
  66. GC.Collect();
  67. Application excel;// = new Application();
  68. int rowIndex=4;
  69. int colIndex=1;
  70. _Workbook xBk;
  71. _Worksheet xSt;
  72. excel= new ApplicationClass();
  73. xBk = excel.Workbooks.Add(true);
  74. xSt = (_Worksheet)xBk.ActiveSheet;
  75. //
  76. //取得标题
  77. //
  78. foreach(DataColumn col in dv.Table.Columns)
  79. {
  80. colIndex++;
  81. excel.Cells[4,colIndex] = col.ColumnName;
  82. xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置标题格
  83. 式为居中对齐
  84. }
  85. //
  86. //取得表格中的数据
  87. //
  88. foreach(DataRowView row in dv)
  89. {
  90. rowIndex ++;
  91. colIndex = 1;
  92. foreach(DataColumn col in dv.Table.Columns)
  93. {
  94. colIndex ++;
  95. if(col.DataType == System.Type.GetType("System.DateTime"))
  96. {
  97. excel.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
  98. xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment =
  99. XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
  100. }
  101. else
  102. if(col.DataType == System.Type.GetType("System.String"))
  103. {
  104. excel.Cells[rowIndex,colIndex] = "’"+row[col.ColumnName].ToString();
  105. xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment =
  106. XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
  107. }
  108. else
  109. {
  110. excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
  111. }
  112. }
  113. }
  114. //
  115. //加载一个合计行
  116. //
  117. int rowSum = rowIndex + 1;
  118. int colSum = 2;
  119. excel.Cells[rowSum,2] = "合计";
  120. xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
  121. //
  122. //设置选中的部分的颜色
  123. //
  124. xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
  125. xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有
  126. 56种
  127. //
  128. //取得整个报表的标题
  129. //
  130. excel.Cells[2,2] = str;
  131. //
  132. //设置整个报表的标题格式
  133. //
  134. xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
  135. xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;
  136. //
  137. //设置报表表格为最适应宽度
  138. //
  139. xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
  140. xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
  141. //
  142. //设置整个报表的标题为跨列居中
  143. //
  144. xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();
  145. xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
  146. //
  147. //绘制边框
  148. //
  149. xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
  150. xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight =
  151. XlBorderWeight.xlThick;//设置左边线加粗
  152. xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight =
  153. XlBorderWeight.xlThick;//设置上边线加粗
  154. xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight =
  155. XlBorderWeight.xlThick;//设置右边线加粗
  156. xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight =
  157. XlBorderWeight.xlThick;//设置下边线加粗
  158. //
  159. //显示效果
  160. //
  161. excel.Visible=true;
  162. //xSt.Export(Server.MapPath(".")
  163. +"file://"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportForma
  164. t.ssExportHTML/);
  165. xBk.SaveCopyAs(Server.MapPath(".")+"file://"+this.xlfile.Text+".xls/ ");
  166. ds = null;
  167. xBk.Close(false, null,null);
  168. excel.Quit();
  169. System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
  170. System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
  171. System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
  172. xBk = null;
  173. excel = null;
  174. xSt = null;
  175. GC.Collect();
  176. string path = Server.MapPath(this.xlfile.Text+".xls");
  177. System.IO.FileInfo file = new System.IO.FileInfo(path);
  178. Response.Clear();
  179. Response.Charset="GB2312";
  180. Response.ContentEncoding=System.Text.Encoding.UTF8;
  181. // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
  182. Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
  183. // 添加头信息,指定文件大小,让浏览器能够显示下载进度
  184. Response.AddHeader("Content-Length", file.Length.ToString());
  185. // 指定返回的是一个不能被客户端读取的流,必须被下载
  186. Response.ContentType = "application/ms-excel";
  187. // 把文件流发送到客户端
  188. Response.WriteFile(file.FullName);
  189. // 停止页面的执行
  190. Response.End();
  191. }