关于Npoi+excel文件读取,修改文件内容的处理方式

因最近有需求场景,实现对文件的读写操作,又不单独生成新的文件,对于源文件的修改,做了一个简单实现,如下↓


 1 // 要操作的excel文件路径
 2             string fileName = Server.MapPath("~/Content/test.xlsx");
 3             if (!System.IO.File.Exists(fileName)) return Content("文件不存在!");
 4             IWorkbook workbook;
 5 
 6             //把文件内容导入到工作薄当中,然后关闭文件
 7             FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
 8 
 9             workbook = WorkbookFactory.Create(fs);
10             fs.Close();//编辑工作薄当中内容            
11             ISheet sheet = workbook.GetSheetAt(0);
12 
13 
14             //workbook.GetSheetAt(0).GetRow(0).Cells[0].SetCellValue("TestCell");
15             for (int i = 0; i <= sheet.LastRowNum; i++)
16             {
17                 foreach (ICell cell in sheet.GetRow(i).Cells)
18                 {
23                     cell.SetCellType(cell.CellType);
24                     if (cell.CellType == CellType.Numeric)
25                     {
26                         if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型
27                         {
28                             cell.SetCellValue(cell.DateCellValue.ToString());
29                         }
30                         else//其他数字类型
31                         {
32                             cell.SetCellValue(cell.NumericCellValue.ToString());
33                         }
34                     }
35                     else
36                     {
37                         cell.SetCellValue(cell.StringCellValue.ToString());
38                     }
39                 }
40                 if (i != 0)
41                 {
42                     ICell firstCell = sheet.GetRow(i).Cells[0];
43                     firstCell.SetCellType(firstCell.CellType);
44                     var cellValue = firstCell.StringCellValue.ToDecimal().ToString();
45                     firstCell.SetCellValue(cellValue);
46                 }
47             }
48 
49             //把编辑过后的工作薄重新保存为excel文件
50             FileStream fs2 = System.IO.File.Create(fileName);
51             workbook.Write(fs2);
52             fs2.Close();
53             return Content("操作成功!!" + DateTime.Now);

读取文件内容更新文件状态

 1 // 要操作的excel文件路径
 2             string fileName = Server.MapPath("~/Content/test.xlsx");
 3             if (!System.IO.File.Exists(fileName)) return Content("文件不存在,请检查路径及文件名称是否正确!");
 4             //IWorkbook workbook;
 5             //把文件内容导入到工作薄当中,然后关闭文件
 6             //FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
 7             //workbook = WorkbookFactory.Create(fs);
 8             //fs.Close();//编辑工作薄当中内容     
 9             //如果是xls,使用HSSFWorkbook;如果是xlsx,使用XSSFWorkbook
10             XSSFWorkbook xssFWorkbook;
11             using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
12             {
13                 xssFWorkbook = new XSSFWorkbook(file);
14             }
15 
16             ISheet sheet = xssFWorkbook.GetSheetAt(0);
17             var userList = GetUserLists(sheet);
18             var userNames = userList.Select(u =>
19             {
20                 return u.UserName.Replace(u.UserName, $"'{u.UserName}'");
21             });
22             var companyNames = userList.Select(u =>
23             {
24                 return u.CompanyName.Replace(u.CompanyName, $"'{u.CompanyName}'");
25             });
26 
27             var userIdCards = userList.Select((u, i) =>
28              {
29                  return $" SELECT '{u.UserName}' AS UserName,'{u.CompanyName}' AS CompanyName,'{u.LegalPersonIdNumber}' AS LegalPersonIdNumber ";
30              });
31             var dataList = AsyncHelper.RunSync(() => _userIdFileAppService.RunSearchAndUpdateData(
32                 new UserIdentityCardInput
33                 {
34                     UserNameString = string.Join(",", userNames),
35                     CompanyNameString = string.Join(",", companyNames),
36                     UserIdCardString = string.Format(@"SELECT * INTO #tbUserIdCardTable FROM ( {0} ) a;", string.Join("  UNION  ", userIdCards))
37                 }
38                 ));
39             for (int i = 0; i <= sheet.LastRowNum; i++)
40             {
41                 if (i != 0)
42                 {
43                     var userName = sheet.GetRow(i).Cells[0].ToString();
44                     var companyName = sheet.GetRow(i).Cells[1].ToString();
45                     //添加列
46                     ICell lastCell = sheet.GetRow(i).CreateCell(3);
47                     lastCell.SetCellType(lastCell.CellType);
48                     ICellStyle newStyle = xssFWorkbook.CreateCellStyle();
49                     //XSSFCellStyle styleTemp = ((XSSFCellStyle)newStyle);
50                     //HSSFPalette palette = xssFWorkbook.GetCustomPalette();
51 
52                     if (dataList.Find(a => a.UserName == userName && a.CompanyName == companyName) != null)
53                     {
54                         lastCell.SetCellValue("已更新");
55                         //Color c = Color.FromArgb(98, 185, 106);
56                         //palette.SetColorAtIndex((short)9, c.R, c.G, c.B);
57                         //var color = palette.FindColor(c.R, c.G, c.B);
58                         //newStyle.FillPattern = FillPattern.SolidForeground;
59                         //newStyle.FillForegroundColor = color.Indexed;
60 
61                         XSSFColor color = new XSSFColor();
62                         color.SetRgb(new byte[] { 255, 255, 0 });
63                         newStyle.FillPattern = FillPattern.SolidForeground;
64                         newStyle.FillForegroundColor = 13;
65                     }
66                     else
67                     {
68                         lastCell.SetCellValue("未更新");
69                         //创建字体
70                         XSSFFont ffont = (XSSFFont)xssFWorkbook.CreateFont();
71                         XSSFColor color = new XSSFColor();
72                         color.SetRgb(new byte[] { 255, 51, 0 });
73                         //给字体设置颜色
74                         ffont.Color = color.Indexed;
75                         //给样式添加字体
76                         newStyle.SetFont(ffont);
77 
78                         newStyle.FillPattern = FillPattern.SolidForeground;
79                         newStyle.FillForegroundColor = 10;
80 
81                     }
82                     lastCell.CellStyle = newStyle;
83                 }
84             }
85 
86             //把编辑过后的工作薄重新保存为excel文件
87             FileStream fs2 = System.IO.File.Create(fileName);
88             xssFWorkbook.Write(fs2);
89             fs2.Close();
90             return Content("操作成功!!" + DateTime.Now);
posted @ 2019-08-20 16:24  麋鹿星空  阅读(2074)  评论(0编辑  收藏  举报