欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jxl解析excel文件的简单例子

程序员文章站 2022-04-09 09:29:07
...

项目中用到,简单记录下来,以后有用:

package com.nantian.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;

public class ExcelUtil {

	public List readContentFromExcel(String filename) {
		Workbook workbook = null;
		try {
			File file = new File(filename);
			InputStream is = new FileInputStream(file);
			workbook = Workbook.getWorkbook(is);//得到工作表
			List total = new ArrayList();
			for (int i = 0; i < workbook.getNumberOfSheets(); i++) {//遍历每个工作簿
				Sheet sheet = workbook.getSheet(i);
				Cell cell = null;
				String data = null;
				List list = new ArrayList();
				for (int j = 0; j < sheet.getRows(); j++) {//遍历每一行
					if(j == 0)continue;//忽略第一行标题行
					Map map = new HashMap();
					for (int k = 0; k < sheet.getColumns(); k++) {//遍历每个单元格
						cell = sheet.getCell(k, j);// 注意 先是列 后是行
						if (cell.getType() == CellType.LABEL) {// 如果数据类型是label的
							data = cell.getContents();
						} else if (cell.getType() == CellType.NUMBER) {// 如果数据类型是number类型的
							NumberCell nc = (NumberCell) cell;
							data = nc.getValue() + "";
						} else if (cell.getType() == CellType.DATE) {//日期类型
							DateCell cd = (DateCell) cell;
							data = cd.getDate() + "";
						}
						map.put("column" + k, data);
					}
					list.add(map);
				}
				total.add(list);
			}
			return total;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("科目导入出错!");
		} finally {
			if (workbook != null)
				workbook.close();
		}
	}

}

 备注:注意解析完成后应关闭资源,尤其是当excel文件过大时。