日期:2014-05-20 浏览次数:20394 次
Response.ContentType = "application/x-msexcel"; Response.ContentEncoding = System.Text.Encoding.Default; Response.AddHeader("content-disposition","attachment; filename=PhoneModelColor.xls"); DataTable dt = (DataTable)Session["Color"]; StringBuilder sb = new StringBuilder(); sb.Append("<META Http-Equiv='Content-Type' Content='text/html; charset=gb2312'>"); sb.Append("<table border='1'>"); sb.Append("<tr><td>Phone Model</td><td>Color Code</td><td>Chinese</td><td>English</td><td>Description</td></tr>"); for(int i=0;i<dt.Rows.Count;i++) { sb.Append("<tr>"); sb.Append("<td>"+dt.Rows[i]["Name"].ToString()+"</td>"); sb.Append("<td>"+"'"+dt.Rows[i]["Color_Code"].ToString()+"</td>"); sb.Append("<td>"+dt.Rows[i]["NameCh"].ToString()+"</td>"); sb.Append("<td>"+dt.Rows[i]["NameEng"].ToString()+"</td>"); sb.Append("<td>"+dt.Rows[i]["Desc"].ToString()+"</td>"); sb.Append("</tr>"); } sb.Append("</table>"); Response.Write(sb.ToString()); Response.End();
private void ExportExcel(DataTable dt, string _strTitle) { string newpath = Server.MapPath(".") + @"\" + Guid.NewGuid() + ".xls"; _excel.Application app = new _excel.Application(); _excel.Workbooks wbooks = app.Workbooks; _excel.Workbook wbook = wbooks.Add(System.Reflection.Missing.Value); //VS2003中最好不要如下创建 // _excel.Workbook wbook = app.Workbooks.Add(System.Reflection.Missing.Value); _excel.Worksheet tsheet = (_excel.Worksheet)wbook.ActiveSheet; //为 tsheet.Cells 创建 Range ,方便释放资源 _excel.Range rans = (_excel.Range)tsheet.Cells; //创建ran为了下面赋值时候使用 _excel.Range ran = null; for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { ran = (_excel.Range)rans[i + 1, j + 1]; ran.Value2 = dt.Rows[i][j]; NAR(ran); //不要如下方式赋值 //tsheet.Cells[i + 1, j + 1] = dt.Rows[i][j]; } } NAR(rans); NAR(tsheet); //保存信息 wbook.Close(true,newpath, System.Reflection.Missing.Value); NAR(wbook); NAR(wbooks); app.Quit(); NAR(app); } /// <summary> /// 释放资源 /// </summary> /// <param name="o"></param> private void NAR(object o) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(o); } catch { } finally { o = null; } }