记录使用NPOI对Excel表进行简单操作,核心代码如下:
/// <summary> /// 在原表的基础上添加一个新表,如果出现名字重复,则覆盖旧表格 /// </summary> public void WriteExcel() { //private List<WebData> WebDatas;WebDatas是一个List if (WebDatas.Count <= 0) { return; } string path = RootPath + "/弹幕信息表.xls"; WebDatas.Sort(new MyDataCort<WebData>()); //这里是一个重写的排序方法 try { FileStream fileR = new FileStream(path, FileMode.Open, FileAccess.Read); HSSFWorkbook workbook = new HSSFWorkbook(fileR); //先读原表格,再添加新表格 string sheetName = DateTime.Now.ToLongDateString().ToString(); ISheet temp = workbook.GetSheet(sheetName); //查看表格是否存在 if (temp == null) //不存在直接创建 { Write(workbook, path, sheetName); Debug.Log("内容添加成功!"); GameRunManager.Instance.TooltipFunc("保存成功!"); } else //存在 删除后创建新的 { int index = workbook.GetSheetIndex(temp); workbook.RemoveSheetAt(index); Write(workbook, path, sheetName); Debug.Log("覆盖!"); GameRunManager.Instance.TooltipFunc("保存成功!"); } fileR.Dispose(); workbook.Close(); } catch (Exception ex) { Debug.Log(ex.Message); GameRunManager.Instance.TooltipFunc("保存失败,重新保存!"); } } private void Write(HSSFWorkbook workbook, string path, string sheetName) { ISheet sheet = workbook.CreateSheet(sheetName); //创建一个新的表 ICellStyle cellStyle = workbook.CreateCellStyle(); //创建一个样式 cellStyle.Alignment = HorizontalAlignment.Center; //水平对齐模式为水平居中 string[] titles = new string[4] { "编号", "学号", "姓名", "课程评价" }; IRow row = sheet.CreateRow(0); //创建标题行 for (int i = 0; i < titles.Length; i++) { if (i < titles.Length - 1) { sheet.SetDefaultColumnStyle(i, cellStyle); //设置样式 } ICell cellId = row.CreateCell(i); //创建单元格 cellId.SetCellValue(titles[i]); //单元格写入内容 } sheet.SetColumnWidth(3, 50 * 256); //设置某一列的宽度 //遍历集合,生成行 int index = 1; //从1行开始写入 for (int i = 0; i < WebDatas.Count; i++) { int x = index + i; IRow rowi = sheet.CreateRow(x); //创建新行 ICell id = rowi.CreateCell(0); //创建一个新元素 id.SetCellValue(WebDatas[i].Id.ToString()); //给新元素添加数据 ICell sno = rowi.CreateCell(1); sno.SetCellValue(WebDatas[i].Sno); ICell name = rowi.CreateCell(2); name.SetCellValue(WebDatas[i].Name); ICell content = rowi.CreateCell(3); content.SetCellValue(WebDatas[i].Content); } FileStream fileW = new FileStream(path, FileMode.Open, FileAccess.Write); workbook.Write(fileW); fileW.Dispose(); }