NPOI 读取Excel文件

Posted 蓝雨冰城

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NPOI 读取Excel文件相关的知识,希望对你有一定的参考价值。

      private void buttonExcel_Click(object sender, EventArgs e)
        { 
            FileStream fs = null;
            List<ISheet> lstISheet = new List<ISheet>();
            string Msg = "";
            string filePath = "";
            //初始化一个OpenFileDialog类
            OpenFileDialog fileDialog = new OpenFileDialog();
            //判断用户是否正确的选择了文件
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                //获取用户选择文件的后缀名
                string extension = Path.GetExtension(fileDialog.FileName);
                //声明允许的后缀名
                string[] str = new string[] { ".xls", ".xlsx" };
                if (!((IList)str).Contains(extension))
                {
                    MessageBox.Show("仅能选择Excel文件");
                }
                else
                {
                    filePath = fileDialog.FileName; 
                }
            }
            if(filePath!="")
            {
                IWorkbook book2003; IWorkbook book2007;
                bool bl2003 = true; bool bl2007 = true;
                fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                try
                {
                     book2003 = new HSSFWorkbook(fs);// 2003版本   
                     int t = 0;
                     while (true)
                     {
                         try
                         {
                             ISheet sheettemp = book2003.GetSheetAt(t);
                             lstISheet.Add(sheettemp);
                             t = t + 1;
                         }
                         catch (Exception ex)
                         {
                             break;
                         }
                     }
                }
                catch (Exception ex)
                {
                    bl2003 = false;
                    Msg = ex.Message.ToString() + "\r\n" + ex.StackTrace.ToString(); 
                    fs.Dispose();
                    fs.Close();
                }
                //
                if(bl2003==false)
                {
                    fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    try
                    {
                          book2007 = new XSSFWorkbook(fs);// 2007版本
                          int t = 0;
                          while (true)
                          { 
                              try
                              {
                                  ISheet sheettemp = book2007.GetSheetAt(t);
                                  lstISheet.Add(sheettemp);
                                  t = t+1;
                              }
                              catch (Exception ex)
                              {
                                  break;
                              }
                          }
                    }
                    catch (Exception ex)
                    {
                        bl2007 = false;
                        Msg = ex.Message.ToString() + "\r\n" + ex.StackTrace.ToString();
                    }
                  
                }
                ReLstDataTable(lstISheet);
                fs.Dispose();
                fs.Close();
            
            } 
        }
        public List<DataTable> ReLstDataTable(List<ISheet> lstISheet)
        {
            List<DataTable> lstTable = new List<DataTable>();
            for (int t = 0; t < lstISheet.Count; t++)
            {
                ISheet sheet = lstISheet[t];
                int rowCount = sheet.LastRowNum;//总行数
                if (rowCount > 0)
                {
                    IRow firstRow = sheet.GetRow(0);//第一行  
                    int cellCount = firstRow.LastCellNum;//列数
                    DataTable dt = new DataTable();
                    int startRow = 1;//如果第一行是列名,则从第二行开始读取  
                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            if (cell.StringCellValue != null)
                            {
                                DataColumn column = new DataColumn(cell.StringCellValue);
                                dt.Columns.Add(column);
                            }
                        }
                    }
                    //------------------------------------------------
                    //填充行  
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue;

                        DataRow dataRow = dt.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            ICell cell = row.GetCell(j);
                            if (cell == null)
                            {
                                dataRow[j] = "";
                            }
                            else
                            {
                                //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)  
                                switch (cell.CellType)
                                {
                                    case CellType.Blank:
                                        dataRow[j] = "";
                                        break;
                                    case CellType.Numeric:
                                        short format = cell.CellStyle.DataFormat;
                                        //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理  
                                        if (format == 14 || format == 31 || format == 57 || format == 58)
                                            dataRow[j] = cell.DateCellValue;
                                        else
                                            dataRow[j] = cell.NumericCellValue;
                                        break;
                                    case CellType.String:
                                        dataRow[j] = cell.StringCellValue;
                                        break;
                                }
                            }
                        }
                        dt.Rows.Add(dataRow);
                    }
                    //------------------------------------------------
                    lstTable.Add(dt);
                }
            }
            return lstTable;
        }

 

以上是关于NPOI 读取Excel文件的主要内容,如果未能解决你的问题,请参考以下文章

使用NPOI读取Excel文件

NPOI 读取Excel文件

使用NPOI读取Excel到DataTable

NPOI读取Excel,导入数据到Excel练习01

NPOI读取excel文件导出数据, 而此时文件正在打开中抛异常怎么办

Npoi读取Excel