1 #region 读取文件 2 3 4 //通过流的方式获取文件 5 using (FileStream fsRead = new FileStream("123.xlsx", FileMode.Open, FileAccess.Read)) 6 { 7 //创建工作表 8 IWorkbook workBook = WorkbookFactory.Create(fsRead); 9 //获取页 10 ISheet sheet = workBook.GetSheetAt(0); 11 //获取行--最后一行 12 for (int i = 0; i <= sheet.LastRowNum; i++) 13 { 14 IRow row = sheet.GetRow(i); 15 //遍历所有的单元格 16 StringBuilder sb = new StringBuilder(); 17 for (int j = 0; j < row.LastCellNum; j++) 18 { 19 //获取单元格 20 ICell cell = row.GetCell(j); 21 //判断单元格的数据类型 22 if (cell.CellType == CellType.Numeric) 23 { 24 sb.Append(cell.NumericCellValue);//单元格的数据 25 } 26 if (cell.CellType == CellType.String) 27 { 28 sb.Append(cell.StringCellValue); 29 } 30 } 31 Console.WriteLine(sb.ToString()); 32 } 33 Console.ReadKey(); 34 } 35 #endregion 36 37 //写入文件 38 List<Person> list = new List<Person>(); 39 list.Add(new Person() { Name = "卡卡西", Age = 1, Gender = "男" }); 40 list.Add(new Person() { Name = "地主", Age = 2, Gender = "男" }); 41 list.Add(new Person() { Name = "独角兽", Age = 40, Gender = "女" }); 42 list.Add(new Person() { Name = "凤姐", Age = 4, Gender = "女" }); 43 //流 44 using (FileStream fsWrite = new FileStream("person.xlsx", FileMode.Create, FileAccess.Write)) 45 { 46 //创建工作表 47 XSSFWorkbook work = new XSSFWorkbook();//2007 48 //HSSFWorkbook work = new HSSFWorkbook();//2003 改一下 person.xls 49 //创建页 50 ISheet sheet = work.CreateSheet("人"); 51 //创建行 52 for (int i = 0; i < list.Count; i++) 53 { 54 IRow row = sheet.CreateRow(i); 55 ICell cell = row.CreateCell(0, CellType.String); 56 cell.SetCellValue(list[i].Name);//姓名 57 58 ICell cell1 = row.CreateCell(1, CellType.Numeric); 59 cell1.SetCellValue(list[i].Age);//年龄 60 61 ICell cell2 = row.CreateCell(2, CellType.String); 62 cell2.SetCellValue(list[i].Gender);//性别 63 } 64 work.Write(fsWrite); 65 } 66 Console.WriteLine("OK"); 67 } 68 } 69 class Person 70 { 71 public string Name { get; set; } 72 public int Age { get; set; } 73 public string Gender { get; set; } 74 75 }