只是以爲這樣很方便 記錄一下mvc
公司有封裝的方法,不過是查出的Table類型,每次用的時候很都很煩,處理數據也不方便,最主要的是我也沒耐心去看,反正在我看來很麻煩,用的時候很頭疼。仍是習慣經過Model List來處理數據,能夠利用Model Class屬性來處理數據格式等等app
var orders=GetOrders();//獲取訂單列表
//Excel表頭
string[] headerTemp = { "訂單號", "下單時間", "訂單狀態", "店鋪名稱", "商品名稱"};
//對應的Model Class屬性 string[] propertyNameTemp = { "OrderId", "OrderDate", "OrderStatusString", "StoreName", "ProductName"}; #region excel簡單樣式設置 HSSFWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1"); ICellStyle othercolstyle = hssfworkbook.CreateCellStyle(); IFont othercolfont = hssfworkbook.CreateFont(); othercolfont.FontName = "微軟雅黑"; othercolfont.FontHeightInPoints = 12; othercolstyle.SetFont(othercolfont); othercolstyle.VerticalAlignment = VerticalAlignment.Center; othercolstyle.Alignment = HorizontalAlignment.Center; #endregion for (int i = 0; i <= orders.Count; i++) { IRow row = sheet1.CreateRow(i); row.Height = 22 * 16; for (int j = 0; j < headerTemp.Length; j++) { ICell cell = row.CreateCell(j); cell.CellStyle = othercolstyle; sheet1.SetColumnWidth(j, 12 * 256); if (i == 0) {
//第一行設置表頭 cell.SetCellValue(headerTemp[j]); } else { Type temp = orders[i - 1].GetType(); PropertyInfo propertyInfo = temp.GetProperty(propertyNameTemp[j]); object pvalue = propertyInfo.GetValue(orders[i - 1], null); cell.SetCellValue(pvalue == null ? "" : pvalue.ToString()); } } } // 寫入到客戶端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); hssfworkbook.Write(ms); ms.Seek(0, SeekOrigin.Begin); return File(ms, "application/vnd.ms-excel", string.Format("{0}.xls", DateTime.Now));
//上面代碼 return File爲.net mvc中返回方式
//ashx或aspx頁面最後返回方式
//寫入流
MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);spa
if (file != null)
{
// 寫入到客戶端
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpContext.Current.Server.UrlEncode("競猜用戶.xlsx")));
Response.BinaryWrite(file.ToArray());
}.net
每次只須要設置excel表頭和對應的Model屬性就能夠,反射那部分不用動。excel
通常像訂單狀態查出來是int類型的枚舉值,能夠在Model裏擴展枚舉屬性OrderStatusStringcode
public string OrderStatusString { get{return 對應的訂單狀態枚舉;} }