文件流解析excel和txt
上传解析:
HttpPostedFile file = HttpContext.Current.Request.Files[0]; string fileType = Path.GetExtension(file.FileName); Stream s = file.InputStream; DataTable dt = new DataTable(); try { if (fileType.ToLower() == ".txt") { dt.Columns.Add("gameAccount"); StreamReader sr = new StreamReader(s, Encoding.Default); string line; while ((line = sr.ReadLine()) != null) { if (!string.IsNullOrWhiteSpace(line)) { DataRow dr = dt.NewRow(); dr["gameAccount"] = line; dt.Rows.Add(dr); } } } else { dt = ImportExcel(s); } }
解析excel需要引用npoi:
/// <summary> /// 读取Excel内容 /// </summary> /// <param name="inputStream"></param> /// <returns></returns> [NonAction] public DataTable ImportExcel(Stream inputStream) { try { DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook; hssfworkbook = new HSSFWorkbook(inputStream); HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(0); System.Collections.IEnumerator rows = (System.Collections.IEnumerator)sheet.GetRowEnumerator(); HSSFRow headerRow = (HSSFRow)sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { HSSFCell cell = (HSSFCell)headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { HSSFRow row = (HSSFRow)sheet.GetRow(i); DataRow dataRow = dt.NewRow(); if (row == null) continue; for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { dataRow[j] = row.GetCell(j).ToString(); } } dt.Rows.Add(dataRow); } return dt; } catch (Exception ex) { throw ex; } }