Excel導入導出在項目運用中並很多見,傳統的狀況通常都是採用插件的形式走流程,像這種的網上一大把就再也不復述。這裏就寫出完整的思路以及代碼,供你們借鑑。數據庫
1、添加引用dotnet4(網上有,能夠自行下載)app
2、添加導入導出類Entities.csui
1 public class Entities:IDisposable 2 { 3 private string fileName = null; //文件名 4 private static IWorkbook workbook = null; 5 private static FileStream fs = null; 6 private bool disposed; 7 8 public Entities(string fileName) 9 { 10 this.fileName = fileName; 11 disposed = false; 12 13 } 14 15 #region 將excel中的數據導入到DataTable中 16 /// <summary> 17 /// 將excel中的數據導入到DataTable中 18 /// </summary> 19 /// <param name="fileNameurl">表名</param> 20 /// <param name="sheetName">excel工做薄sheet的名稱</param> 21 /// <returns>返回的DataTable</returns> 22 public static DataTable ExcelToDataTableHelper(string fileNameurl, string sheetName) 23 { 24 return ExcelToDataTableHelper(fileNameurl, sheetName, 1); 25 } 26 27 /// <summary> 28 /// 將excel中的數據導入到DataTable中 29 /// </summary> 30 /// <param name="fileNameurl">表名</param> 31 /// <param name="sheetName">excel工做薄sheet的名稱</param> 32 /// <param name="ColumnNum">第幾行是表頭</param> 33 /// <returns>返回的DataTable</returns> 34 public static DataTable ExcelToDataTableHelper(string fileNameurl, string sheetName, int ColumnNum) 35 { 36 ISheet sheet = null; 37 DataTable data = new DataTable(); 38 int startRow = 0; 39 try 40 { 41 fs = new FileStream(fileNameurl, FileMode.Open, FileAccess.Read); 42 if (fileNameurl.IndexOf(".xlsx") > 0) // 2007版本 43 workbook = new XSSFWorkbook(fs); 44 else if (fileNameurl.IndexOf(".xls") > 0) // 2003版本 45 workbook = new HSSFWorkbook(fs); 46 47 if (sheetName != null) 48 { 49 sheet = workbook.GetSheet(sheetName); 50 if (sheet == null) //若是沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet 51 { 52 sheet = workbook.GetSheetAt(0); 53 } 54 } 55 else 56 { 57 sheet = workbook.GetSheetAt(0); 58 } 59 if (sheet != null) 60 { 61 IRow firstRow; 62 63 // firstRow = sheet.GetRow(0); 64 if (ColumnNum > 0) 65 { 66 firstRow = sheet.GetRow(ColumnNum - 1); 67 } 68 else 69 { 70 firstRow = sheet.GetRow(0); 71 } 72 int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數 73 74 for (int i = firstRow.FirstCellNum; i < cellCount; ++i) 75 { 76 ICell cell = firstRow.GetCell(i); 77 if (cell != null) 78 { 79 string cellValue = cell.StringCellValue; 80 if (cellValue != null && cellValue != "") 81 { 82 DataColumn column = new DataColumn(cellValue); 83 data.Columns.Add(column); 84 } 85 } 86 } 87 cellCount = data.Columns.Count; 88 89 //找出第幾行是列名 90 startRow = ColumnNum; 91 92 //startRow = firstDataNum-1; 93 //最後一列的標號 94 int rowCount = sheet.LastRowNum; 95 for (int i = startRow; i <= rowCount; ++i) 96 { 97 IRow row = sheet.GetRow(i); 98 if (row == null) continue; //沒有數據的行默認是null 99 DataRow dataRow = data.NewRow(); 100 for (int j = row.FirstCellNum; j < cellCount; ++j) 101 { 102 if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null 103 { 104 //dataRow[j] = row.GetCell(j).ToString(); 105 //讀取Excel格式,根據格式讀取數據類型 106 ICell cell = row.GetCell(j); 107 dataRow[j] = parseExcel(cell); 108 } 109 } 110 data.Rows.Add(dataRow); 111 } 112 } 113 return data; 114 } 115 catch (Exception ex) 116 { 117 Console.WriteLine("Exception: " + ex.Message); 118 return null; 119 } 120 finally 121 { 122 if (fs != null) 123 fs.Close(); 124 } 125 } 126 127 //格式轉換 128 private static String parseExcel(ICell cell) 129 { 130 string result = ""; 131 switch (cell.CellType) 132 { 133 case CellType.Formula: 134 HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook); 135 result = e.Evaluate(cell).StringValue; 136 break; 137 case CellType.Numeric:// 數字類型 138 if (HSSFDateUtil.IsCellDateFormatted(cell)) 139 {// 處理日期格式、時間格式 140 string sdf = ""; 141 if (cell.CellStyle.DataFormat == HSSFDataFormat 142 .GetBuiltinFormat("h:mm")) 143 { 144 sdf = "HH:mm"; 145 } 146 else 147 {// 日期 148 sdf = "yyyy-MM-dd"; 149 } 150 DateTime date = cell.DateCellValue; 151 result = date.ToString(sdf); 152 } 153 else if (cell.CellStyle.DataFormat == 58) 154 { 155 // 處理自定義日期格式:m月d日(經過判斷單元格的格式id解決,id的值是58) 156 string sdf = "yyyy-MM-dd"; 157 double value = cell.NumericCellValue; 158 DateTime date = new DateTime(1899, 12, 30); // 起始時間 159 date = date.AddDays(value); 160 result = date.ToString(sdf); 161 } 162 else 163 { 164 result = cell.NumericCellValue.ToString(); 165 } 166 break; 167 case CellType.String:// String類型 168 result = cell.StringCellValue; 169 break; 170 case CellType.Blank: 171 result = ""; 172 break; 173 default: 174 result = ""; 175 break; 176 } 177 return result; 178 } 179 180 /// <summary> 181 /// 獲取Exce工做薄名稱 182 /// </summary> 183 /// <param name="fileNameurl"></param> 184 /// <returns></returns> 185 public static List<string> GetSheetNames(string fileNameurl) 186 { 187 using (FileStream sr = new FileStream(fileNameurl, FileMode.OpenOrCreate)) 188 { 189 //根據路徑經過已存在的excel來建立HSSFWorkbook,即整個excel文檔 190 HSSFWorkbook workbook = new HSSFWorkbook(sr); 191 int x = workbook.Workbook.NumSheets; 192 List<string> sheetNames = new List<string>(); 193 for (int i = 0; i < x; i++) 194 { 195 sheetNames.Add(workbook.Workbook.GetSheetName(i)); 196 } 197 return sheetNames; 198 } 199 } 200 201 //資源釋放 202 public void Dispose() 203 { 204 //釋放資源 205 Dispose(true); 206 //告訴垃圾回收器不要調用指定對象的Dispose方法 207 GC.SuppressFinalize(this); 208 } 209 210 protected virtual void Dispose(bool disposing) 211 { 212 if (!this.disposed) 213 { 214 if (disposing) 215 { 216 if (fs != null) 217 fs.Close(); 218 } 219 220 fs = null; 221 disposed = true; 222 } 223 } 224 #endregion 225 }
將Entities類做爲導入導出Excel的中樞this
3、上傳Excel模版lua
選好模版後將之放入文件夾,經過Upload方法實現模版下載url
1 [HttpPost] 2 public ActionResult Upload(HttpPostedFileBase file) 3 { 4 if (file == null) 5 { 6 return Content("沒有文件!", "text/plain"); 7 } 8 var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName)); 9 //string strFilePaht = "~/Upload"; 10 //string filename = Path.GetFileNameWithoutExtension(fileName); //這個就是獲取文件名的 11 Session["filename"] = fileName; 12 try 13 { 14 file.SaveAs(fileName); 15 Response.Write("<script>alert('上傳成功')</script>"); 16 } 17 catch 18 { 19 return Content("上傳異常 !", "text/plain"); 20 } 21 return View(); 22 }
這裏只是一個簡單的文件下載邏輯,後面有待完善spa
4、當下載好模版後將須要導入的Excel數據使用Import方法導入到DataTable,存入到數據庫插件
1 public ActionResult Import() 2 { 3 //繼承來自上傳文件的文件路徑 ,該路徑爲相對路徑 4 string pathName = Session["filename"].ToString(); 5 if (pathName=="") 6 { 7 return Json("erro",JsonRequestBehavior.AllowGet); 8 } 9 string sheet = "Sheet1"; 10 //傳入參數,將excel轉換爲Datatable,格式文件名加上固定模版Sheet1 11 DataTable dt = Infotype.ExcelHelper.Entities.ExcelToDataTableHelper(pathName, sheet); 12 //循環這個集合並添加到數據表 13 int i = 0; 14 foreach (DataRow item in dt.Rows) 15 { 16 tab.ProjectName = item[0].ToString(); 17 tab.InfoTypes = item[1].ToString(); 18 tab.field = item[2].ToString(); 19 tab.fieldtxt = item[3].ToString(); 20 db.InfoTables.Add(tab); 21 i = db.SaveChanges(); 22 } 23 if (i > 0) 24 { 25 return Json("Data", JsonRequestBehavior.AllowGet); 26 } 27 else 28 { 29 return Json("NOData", JsonRequestBehavior.AllowGet); 30 } 31 32 }
5、當修改了數據須要及時導出到Excel時就能夠用到ExportStu2導出了excel
1 public FileResult ExportStu2() 2 { 3 //獲取list數據 4 var checkList = db.InfoTables.Where(r => r.ProjectName != null).Select(r => new { r.ProjectName,r.InfoTypes,r.field,r.fieldtxt }).ToList(); 5 //建立Excel文件的對象 6 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); 7 //添加一個sheet 8 NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1"); 9 10 //給sheet1添加第一行的頭部標題 11 NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0); 12 row1.CreateCell(0).SetCellValue("項目名稱"); 13 row1.CreateCell(1).SetCellValue("信息類型"); 14 row1.CreateCell(2).SetCellValue("字段"); 15 row1.CreateCell(3).SetCellValue("字段名稱"); 16 //....N行 17 18 //將數據逐步寫入sheet1各個行 19 for (int i = 0; i < checkList.Count(); i++) 20 { 21 NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1); 22 rowtemp.CreateCell(0).SetCellValue(checkList[i].ProjectName.ToString()); 23 rowtemp.CreateCell(1).SetCellValue(checkList[i].InfoTypes.ToString()); 24 rowtemp.CreateCell(2).SetCellValue(checkList[i].field.ToString()); 25 rowtemp.CreateCell(3).SetCellValue(checkList[i].fieldtxt.ToString()); 26 //....N行 27 } 28 // 寫入到客戶端 29 System.IO.MemoryStream ms = new System.IO.MemoryStream(); 30 book.Write(ms); 31 ms.Seek(0, SeekOrigin.Begin); 32 DateTime dt = DateTime.Now; 33 string dateTime = dt.ToString("yyMMddHHmmssfff"); 34 string fileName = "查詢結果" + dateTime + ".xls"; 35 return File(ms, "application/vnd.ms-excel", fileName); 36 }
以上爲我使用Excel導入導出的五大步驟,代碼爲示例,可根據實際狀況使用code