用C#读取EXCEL文件文本
之前开发搜索软件的时候用到,需要查找EXCEL文件里面是否含有一些关键字。
需要先安装NPOI:
Install-Package NPOI
示例代码:
using NPOI.SS.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Text; namespace CgdataBase { public class ExcelHelper { private static IWorkbook OpenWorkbook(string fileName) { FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read); return WorkbookFactory.Create(file, true); } public static string ReadAllText(string fileName) { var myList = new StringBuilder(); IWorkbook workbook = OpenWorkbook(fileName); for (int i = 0; i < workbook.NumberOfSheets; i++) { ISheet sheet = workbook.GetSheetAt(i); if (sheet != null) { myList.Append(ReadAllText(sheet)); } } return myList.ToString(); } private static string ReadAllText(ISheet sheet) { var myList = new StringBuilder(); for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row != null) { for (int j = row.FirstCellNum; j <= row.LastCellNum; j++) { var cell = row.GetCell(j); if (cell?.CellType == CellType.String) { myList.Append(cell.StringCellValue); } } } } return myList.ToString(); } } }