using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Windows.Forms;

using NPOI.SS.UserModel;
using NPOI.HSSF.Util;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;  

namespace ExcelDataExtractor
{
    static class TableDataParser
    {
        static IWorkbook hssfworkbook;  
        static public DataTable ImportExcelFile(string filePath)  
        {  
            #region//初始化信息  
            try  
            {                
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))  
                {  
                    hssfworkbook = new HSSFWorkbook(file);  
                }  
            }  
            catch (Exception e)  
            {
                MessageBox.Show("error:"+e.Message+"\n");
                return (DataTable)null;
            }  
            #endregion  
  
            ISheet sheet = hssfworkbook.GetSheetAt(0);  
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            DataTable dt = new DataTable();    
            //一行最后一个方格的编号 即总的列数  
            for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)  
            {  
                dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());  
            }    
            while (rows.MoveNext())  
            {  
                IRow row = (HSSFRow)rows.Current;  
                DataRow dr = dt.NewRow();    
                for (int i = 0; i < row.LastCellNum; i++)  
                {  
                    ICell cell = row.GetCell(i); 
                    if (cell == null)  
                    {  
                        dr[i] = null;  
                    }  
                    else  
                    {  
                        dr[i] = cell.ToString();  
                    }  
                }  
                dt.Rows.Add(dr);  
            }  
            return dt;  
        }  
    }
}

 

相关文章:

  • 2022-12-23
  • 2021-10-30
  • 2022-12-23
  • 2022-12-23
  • 2021-07-20
  • 2021-09-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-05
  • 2022-12-23
  • 2022-12-23
  • 2021-11-13
  • 2021-11-10
  • 2021-05-30
相关资源
相似解决方案