使用NPOI组件读取excel数据
2012-12-21 15:11 Ecin 阅读(713) 评论(1) 编辑 收藏 举报分享一段代码,将excel数据读取到DataTable:
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; namespace ConsoleApp.Utility { public class ExcelBuilder { /// <summary> /// exact excel data into DataTable /// </summary> /// <param name="excel">excel file name</param> /// <param name="index">sheet index </param> /// <param name="header"> the first row in excel whether belongs the columns</param> /// <returns>DataTable</returns> public static DataTable ToDataTable(string excel,int index, bool header) { DataTable dt = new DataTable(Path.GetFileNameWithoutExtension(excel) + "_Sheet" + index); IWorkbook workbook; using (FileStream file = new FileStream(excel, FileMode.Open, FileAccess.Read)) { workbook = new XSSFWorkbook(file); } ISheet sheet = workbook.GetSheetAt(index); var rows = sheet.GetRowEnumerator(); rows.MoveNext(); IRow row = (XSSFRow)rows.Current; for (int i = 0; i < row.LastCellNum; i++) { ICell cell = row.GetCell(i); string columnName = header ? cell.StringCellValue : i.ToString(); dt.Columns.Add(columnName, typeof(string)); } if (!header) { DataRow first = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { ICell cell = row.GetCell(i); first[i] = cell.StringCellValue; } dt.Rows.Add(first); } while (rows.MoveNext()) { row = (XSSFRow)rows.Current; DataRow dataRow = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { ICell cell = row.GetCell(i); dataRow[i] = cell.StringCellValue; } dt.Rows.Add(dataRow); } return dt; } } }
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。