天天看点

Asp.net(c#)NPOI读取excle的工作表

通过NPOI读取excle的工作表

public List<string> GetSheet(String filePath)
        {
            List<string> sheetNames = new List<string>();
            try
            {
                IWorkbook workbook = null;
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                //根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档
                if (filepath.IndexOf(".xlsx") > 0)
                {
                    // 2007版本
                    workbook = new XSSFWorkbook(fs);
                }
                else if (filepath.IndexOf(".xls") > 0)
                {
                    // 2003版本
                    workbook = new HSSFWorkbook(fs);
                }
                //XSSFWorkbook workbook = new XSSFWorkbook(sr);
                int x = workbook.NumberOfSheets;
                for (int i = 0; i < x; i++)
                {
                    sheetNames.Add(workbook.GetSheetName(i).ToString());
                }
            }
            catch(Exception e)
            {
           	 	Console.Out.Write(e.Message);
            }
       
            return sheetNames;
        }