码迷,mamicode.com
首页 > 其他好文 > 详细

EXCEL 读取

时间:2015-11-01 11:22:28      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:

xlsx2007 和 xls2003 两种格式需要使用两种方法
XSSF      HSSF
大数据excel读取参考 http://www.iteye.com/topic/624969
poi-3.9.jar poi-ooxml-3.9.jar poi-ooxml-schemas-3.9.jar xmlbeans-2.3.0.jar


小数据excel读取
package com.aibi.cmdc.webService;

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 org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {

	public static String getCellValue(Cell cell) {
		if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
			// 返回数值类型的值
			return String.valueOf(cell.getNumericCellValue());
		} else {
			// 返回字符串类型的值
			return String.valueOf(cell.getStringCellValue());
		}
	}

	public static List<Map<String, String>> readExcel(String pathName) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		List<String> keys = new ArrayList<String>();
		try {
			InputStream is = new FileInputStream(pathName);
			XSSFWorkbook wk = new XSSFWorkbook(is);
			XSSFSheet hssfSheet = wk.getSheetAt(0);// 取得 第一个sheet页
			XSSFRow titleRow = hssfSheet.getRow(4);// 取得表头
			for (int cellIndex = 0; cellIndex < titleRow.getLastCellNum(); cellIndex++) {
				Cell cell = titleRow.getCell(cellIndex);
				if (cell != null) {
					String cellValue = getCellValue(cell);
					System.out.println(cellValue);
					keys.add(cellValue);
				}
			}
			// 循环行Row
			for (int rowNum = 4; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
				XSSFRow hssfRow = hssfSheet.getRow(rowNum);
				if (hssfRow == null) {
					continue;
				}
				Map<String, String> rowMap = new HashMap<String, String>();
				for (int i = 0; i < hssfRow.getLastCellNum(); i++) {
					Cell cell = hssfRow.getCell(i);
					if (cell != null) {
						rowMap.put(keys.get(i), getCellValue(cell));
					}
				}
				list.add(rowMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// String pathName ="e:\\11.xlsx";
		String pathName = "e:\\aa2.xlsx";
		List<Map<String, String>> list = readExcel(pathName);
		System.out.println(list);

	}

}

  

EXCEL 读取

标签:

原文地址:http://www.cnblogs.com/clds/p/4927377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!