码迷,mamicode.com
首页 > 其他好文 > 详细

Excel 相关

时间:2019-12-16 17:25:31      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:number   tostring   read   xss   http   sheet   erro   getc   mamicode   

技术图片

 

 



1
static public class ImportExcel 2 { 3 public static DataTable GetExcelDataTable(string filePath) 4 { 5 IWorkbook Workbook; 6 DataTable table = new DataTable(); 7 try 8 { 9 using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) 10 { 11 //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式 12 string fileExt = Path.GetExtension(filePath).ToLower(); 13 if (fileExt == ".xls") 14 { 15 Workbook = new HSSFWorkbook(fileStream); 16 } 17 else if (fileExt == ".xlsx") 18 { 19 Workbook = new XSSFWorkbook(fileStream); 20 } 21 else 22 { 23 Workbook = null; 24 } 25 } 26 } 27 catch (Exception ex) 28 { 29 throw ex; 30 } 31 //定位在第一个sheetActiveSheetIndex 32 ISheet sheet = Workbook.GetSheetAt(0); 33 //int sheet1 = Workbook.NumberOfSheets;//总共有多少页码 34 //第一行为标题行 35 IRow headerRow = sheet.GetRow(0); 36 int cellCount = headerRow.LastCellNum; 37 int rowCount = sheet.LastRowNum; 38 39 //循环添加标题列 40 for (int i = headerRow.FirstCellNum; i < cellCount; i++) 41 { 42 DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); 43 table.Columns.Add(column); 44 } 45 46 //数据 47 for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++) 48 { 49 IRow row = sheet.GetRow(i); 50 DataRow dataRow = table.NewRow(); 51 if (row != null) 52 { 53 for (int j = row.FirstCellNum; j < cellCount; j++) 54 { 55 if (row.GetCell(j) != null) 56 { 57 dataRow[j] = GetCellValue(row.GetCell(j)); 58 } 59 } 60 } 61 table.Rows.Add(dataRow); 62 } 63 return table; 64 } 65 66 private static string GetCellValue(ICell cell) 67 { 68 if (cell == null) 69 { 70 return string.Empty; 71 } 72 73 switch (cell.CellType) 74 { 75 case CellType.Blank: 76 return string.Empty; 77 case CellType.Boolean: 78 return cell.BooleanCellValue.ToString(); 79 case CellType.Error: 80 return cell.ErrorCellValue.ToString(); 81 case CellType.Numeric: 82 case CellType.Unknown: 83 default: 84 return cell.ToString(); 85 case CellType.String: 86 return cell.StringCellValue; 87 case CellType.Formula: 88 try 89 { 90 HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook); 91 e.EvaluateInCell(cell); 92 return cell.ToString(); 93 } 94 catch 95 { 96 return cell.NumericCellValue.ToString(); 97 } 98 } 99 } 100 }

Excel 相关

标签:number   tostring   read   xss   http   sheet   erro   getc   mamicode   

原文地址:https://www.cnblogs.com/YZM97/p/12050009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!