当前位置: 移动技术网 > IT编程>开发语言>c# > 读取ecxel中数据

读取ecxel中数据

2020年03月14日  | 移动技术网IT编程  | 我要评论
//在NuGet中导入NPOI.Excel管理器 /// </summary> /// 读取Excel,放入DataTable中 /// <param name="fileName">文件路劲</param> /// <param name="sheetName">表名</param> /// <p ...

//在nuget中导入npoi.excel管理器



 /// </summary>
        /// 读取excel,放入datatable中
        /// <param name="filename">文件路劲</param>
        /// <param name="sheetname">表名</param>
        /// <param name="isfirstrowcolumn">是否有表头</param>
        /// <returns></returns>
public static datatable readexceltodatatable(string filename, string sheetname = null, bool isfirstrowcolumn = false) { //定义要返回的datatable对象 datatable data = new datatable(); npoi.ss.usermodel.isheet sheet = null; //数据开始行(排除标题行) int startrow = 0; if (!file.exists(filename)) { return null; } //根据指定路径读取文件 filestream fs = new filestream(filename, filemode.open, fileaccess.read); npoi.ss.usermodel.iworkbook workbook = npoi.ss.usermodel.workbookfactory.create(fs); //iworkbook workbook = new hssfworkbook(fs); //如果有指定工作表名称 if (!string.isnullorempty(sheetname)) { sheet = workbook.getsheet(sheetname); //如果没有找到指定的sheetname对应的sheet,则尝试获取第一个sheet if (sheet == null) { sheet = workbook.getsheetat(0); } } else { //如果没有指定的sheetname,则尝试获取第一个sheet sheet = workbook.getsheetat(0); } if (sheet != null) { npoi.ss.usermodel.irow firstrow = sheet.getrow(0); //一行最后一个cell的编号 即总的列数 int cellcount = firstrow.lastcellnum; //如果第一行是标题列名 for (int i = firstrow.firstcellnum; i < cellcount; ++i) { npoi.ss.usermodel.icell cell = firstrow.getcell(i); if (cell != null) //遍历excel表 { // string cellvalue = cell.stringcellvalue; if (cell != null) { datacolumn column = new datacolumn(cell.tostring()); data.columns.add(column); } } } if (isfirstrowcolumn) { startrow = sheet.firstrownum + 1; //有表头时不读取表头 } else { startrow = sheet.firstrownum; } //最后一列的标号 int rowcount = sheet.lastrownum; for (int i = startrow; i <= rowcount; ++i) { npoi.ss.usermodel.irow row = sheet.getrow(i); if (row == null) continue; //没有数据的行默认是null        datarow datarow = data.newrow(); for (int j = row.firstcellnum; j < cellcount; ++j) { if (row.getcell(j) != null) //同理,没有数据的单元格都默认是null datarow[j] = row.getcell(j).tostring(); } data.rows.add(datarow); } } return data; }

非原创

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网