Dotnet6 NPOI操作Excel基本操作总结
|
背景
- 需要对Excel进行读取和写入,目前使用Dotnet6开发环境,故直接使用。
- 达到的效果:兼容.xls和.xlsx,识别行为空自动跳过,识别显示值,识别格式内容
步骤
- Dotnet 6Nuget 安装 NPOI, 具体版本 2.6.1,tips: 搜索资料时,可能NPOI 1 与 NPOI 2 可能有出入。
使用方法
- public static IWorkbook OpenWorkbook(string path)
- {
- using (var stream = File.OpenRead(path))
- {
- if (Path.GetExtension(path) == ".xls")
- return new HSSFWorkbook(stream);
- else
- return new XSSFWorkbook(stream);
- }
- }
复制代码
- 根据序号获取相应sheet对象,并复制该sheet,添加到原Excel第一个
- public static void MoveAndCopySheet(string path, int index = 0)
- {
- var workbook = OpenWorkbook(path);
- var sheet = workbook.GetSheetAt(index);
- if (sheet == null)
- throw new Exception($"Sheet 'At {index}' not found.");
-
- var clonedSheet = workbook.CloneSheet(0);
- var cloneSheetName = $"{sheet.SheetName}_copy_{DateTime.Now.ToShortTimeString().Replace(":","-")}";
- workbook.SetSheetName(workbook.GetSheetIndex(clonedSheet), cloneSheetName);
- workbook.SetSheetOrder(cloneSheetName, 0);
- using (var stream = File.OpenWrite(path))
- {
- workbook.Write(stream);
- }
- }
复制代码- public static void MoveAndCopySheet(string path, string sheetName)
- {
- var workbook = OpenWorkbook(path);
- var sheet = workbook.GetSheet(sheetName);
- if (sheet == null)
- throw new Exception($"Sheet '{sheetName}' not found.");
- workbook.SetSheetOrder(sheetName, 0);
- var clonedSheet = workbook.CloneSheet(0);
- workbook.SetSheetName(workbook.GetSheetIndex(clonedSheet), sheetName + "_copy");
- using (var stream = File.OpenWrite(path))
- {
- workbook.Write(stream);
- }
- }
复制代码 [code] public static void ProcessRows(string path, string sheetName) { var workbook = OpenWorkbook(path); var sheet = workbook.GetSheet(sheetName); if (sheet == null) throw new Exception($"Sheet '{sheetName}' not found."); for (int rowIndex = 0; rowIndex |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
x
|
|
|
发表于 2023-9-4 14:40:26
举报
回复
分享
|
|
|
|