码迷,mamicode.com
首页 > 其他好文 > 详细

NPOI 读取Excel文件

时间:2018-02-13 18:51:34      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:读取excel   npoi   gets   str   etc   continue   col   for   rac   

      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文件

标签:读取excel   npoi   gets   str   etc   continue   col   for   rac   

原文地址:https://www.cnblogs.com/lanyubaicl/p/8447027.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!