Hero is coming back

风吹呀吹

风会指引你前进的方向

C# NPOI excel文件转datatable

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

 

public DataTable ExcelToDataTable(string excelPath)
        {
            IWorkbook workbook;
            using (FileStream stream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
            {
                workbook = new XSSFWorkbook(stream);
            }

            ISheet sheet = workbook.GetSheetAt(0); // zero-based index of your target sheet
            DataTable dt = new DataTable(sheet.SheetName);

            // write header row
            IRow headerRow = sheet.GetRow(0);
            foreach (ICell headerCell in headerRow)
            {
                dt.Columns.Add(headerCell.ToString());
            }

            // write the rest
            int rowIndex = 0;
            foreach (IRow row in sheet)
            {
                // skip header row
                if (rowIndex++ == 0) continue;
                DataRow dataRow = dt.NewRow();
                dataRow.ItemArray = row.Cells.Select(c => c.ToString()).ToArray();
                dt.Rows.Add(dataRow);
            }
            return dt;
        }

 NPOI下载地址:点击下载

posted @ 2017-11-15 15:28  风吹呀吹  阅读(908)  评论(0编辑  收藏  举报