.net XSSFWorkbook 读取/写入 指定单元格的内容

发布于:2024-12-06 ⋅ 阅读:(148) ⋅ 点赞:(0)

方法如下:

 using NPOI.SS.Formula.Functions;
 using NPOI.SS.UserModel;
 using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
 using OfficeOpenXml.FormulaParsing.Excel.Functions.Numeric;

 /// <summary>
 /// 读取Excel指定单元格内容
 /// </summary>
 /// <param name="sheet">Excel</param>
 /// <param name="r">行index</param>
 /// <param name="c">列index</param>
 /// <returns>string值</returns>
 public string GetCellValue(ISheet sheet, int r, int c)
 {
     IRow row = sheet.GetRow(r);
     ICell cell = row.GetCell(c);

     object obj = cell.ToString();
     string value = cell.StringCellValue;
     return value;
 }

 /// <summary>
 /// 设置Excel指定单元格内容
 /// </summary>
 /// <param name="sheet">Excel</param>
 /// <param name="r">行index</param>
 /// <param name="c">列index</param>
 /// <param name="value">单元格内容</param>
 /// <returns></returns>
 public void SetCellValue(ISheet sheet, int r, int c, string value)
 {
     if (!string.IsNullOrWhiteSpace(value))
     {
         IRow row = sheet.GetRow(r);
         ICell cell = row.GetCell(c);
         cell.SetCellValue(value);
     }
 }

模板参考


说明:

①横坐标0~8对应Row的index,纵坐标0~25对应Cell的index

②根据①的横纵坐标,找到Excle的单元格子,可以进行:读取数据 StringCellValue 和 写入数据 SetCellValue

③如果单元格是几个格子合并后的,则读写数据以 合并前第一个格子为准  


实际应用

https://blog.csdn.net/djk8888/article/details/144130679

 


网站公告

今日签到

点亮在社区的每一天
去签到