java 读取excel文件包括( XX.xls、XX.xlsx)

1.下载poi相关jar包http://www.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin-3.8-20120326.zip

2.导入java包dom4j-1.6.1.jar、poi-3.8-20120326.jar、poi-ooxml-3.8-20120326.jar、poi-ooxml-schemas-3.8-20120326.jar、xbean.jar

3.实现代码 :

package servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcleTest {
	public static void main(String[] args) {
		String path = "E:/yy.xls";
		//String path = "E:/yy.xlsx";
		Map<String, List<String[]>> map = getExcle(path);
		List<String[]> list = map.get("Sheet1");
		for (int i = 0; i < list.size(); i++) {
			String[] str = list.get(i);
			for (int j = 0; j < str.length; j++) {
				System.out.print(str[j] + "   |   ");
			}
			System.out.println("");
		}
	}

	/**
	 *获得excle的数据
	 * 
	 * @param pathname
	 * @return
	 */
	public static Map<String, List<String[]>> getExcle(String pathname) {
		InputStream fs = null;
		Workbook wb = null;
		Map<String, List<String[]>> map = new HashMap<String, List<String[]>>();
		try {
			// excle的类型
			String readType = pathname.substring(pathname.lastIndexOf("."));
			File file = new File(pathname);
			if (file.exists()) {
				fs = new FileInputStream(file);
			} else {
				System.out.println("文件不存在!");
			}
			if (readType.equals(".xls")) {
				wb = new HSSFWorkbook(fs);
			} else  {
				wb = new XSSFWorkbook(fs);
			} 
			map = getExcleData_xls(wb);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 获得excle xls格式的数据
	 * 
	 * @param wb
	 * @return
	 */
	public static Map<String, List<String[]>> getExcleData_xls(Workbook wb) {
		Map<String, List<String[]>> map = new HashMap<String, List<String[]>>();
		try {
			if (wb != null) {
				// sheet个数
				int numSheet = wb.getNumberOfSheets();
				for (int i = 0; i < numSheet; i++) {
					Sheet sheet = wb.getSheetAt(i);
					String sheetname = sheet.getSheetName();
					List<String[]> listData = getSheetData(sheet); // 读取sheet里的数据
					listData = setMergedRegion(sheet, listData);
					map.put(sheetname, listData);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 获得sheet 里的数据
	 * 
	 * @param sheet
	 * @return
	 */
	public static List<String[]> getSheetData(Sheet sheet) {
		List<String[]> listData = new ArrayList<String[]>();
		try {
			if (sheet != null) {
				for (int i = 0; i <= sheet.getLastRowNum(); i++) {
					Row row = sheet.getRow(i);
					String[] rowData = getRowData(row);
					listData.add(rowData);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return listData;
	}

	/**
	 * 获得row 的数据
	 * 
	 * @param row
	 * @return
	 */
	public static String[] getRowData(Row row) {
		String[] rowData = null;
		try {
			if (row != null) {
				int numcell = row.getLastCellNum();
				rowData = new String[numcell];
				for (int i = 0; i < numcell; i++) {
					Cell cell = row.getCell(i);
					rowData[i] = getCellData(cell);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rowData;
	}
	/**
	 * 获得单元格的值 
	 * @param cell
	 * @return
	 */
	public static String getCellData(Cell cell) {
		String value = null;
		try {
			if (cell != null) {
				switch (cell.getCellType()) {
				case Cell.CELL_TYPE_NUMERIC: // 数值型
					if (DateUtil.isCellDateFormatted(cell)) {
						// 如果是Date类型则 ,获取该Cell的Date值
						value =new SimpleDateFormat("yyyy-MM-dd").format(DateUtil
								.getJavaDate(cell.getNumericCellValue()));
					} else {// 纯数字,这里要判断是否为小数的情况,因为整数在写入时会被加上小数点
						String t = cell.getNumericCellValue() + "";
						BigDecimal n = new BigDecimal(cell
								.getNumericCellValue());
						// 判断是否有小数点
						if (t.indexOf(".") < 0) {
							value = n.intValue() + "";
						} else {
							// 数字格式化对象
							NumberFormat nf = NumberFormat.getInstance();
							// 小数点最大两位
							nf.setMaximumFractionDigits(2);
							// 执行格式化
							value = nf.format(n.doubleValue());
						}
					}
					break;
				case Cell.CELL_TYPE_STRING: // 字符串型
					value = cell.getRichStringCellValue().toString();
					break;
				case Cell.CELL_TYPE_FORMULA:// 公式型
					// 读公式计算值
					value = String.valueOf(cell.getNumericCellValue());
					break;
				case Cell.CELL_TYPE_BOOLEAN:// 布尔
					value = " " + cell.getBooleanCellValue();
					break;
				/* 此行表示该单元格值为空 */
				case Cell.CELL_TYPE_BLANK: // 空值
					value = " ";
					break;
				case Cell.CELL_TYPE_ERROR: // 故障
					value = " ";
					break;
				default:
					value = cell.getRichStringCellValue().toString();
				}
			}
		} catch (Exception e) {
			 e.printStackTrace();
		}
		return value;
	}

	/**
	 * 处理单元格值相等的单元格
	 * 
	 * @param sheet
	 */
	@SuppressWarnings("unused")
	public static List<String[]> setMergedRegion(Sheet sheet,
			List<String[]> list) {
		int num = sheet.getNumMergedRegions();
		List<String[]> listDate = new ArrayList<String[]>();
		try {

			for (int i = 0; i < num; i++) {
				CellRangeAddress rangeAddress = sheet.getMergedRegion(i);
				int firstcell = rangeAddress.getFirstColumn();
				int firstrow = rangeAddress.getFirstRow();
				int lastcell = rangeAddress.getLastColumn();
				int lastrow = rangeAddress.getLastRow();
				// 处理合并行的值
				if (firstcell == lastcell) {
					for (int j = firstrow; j <= lastrow; j++) {
						list.get(j)[firstcell] = list.get(firstrow)[firstcell];
					}
				}
				// 处理合并列的值
				if (firstrow == lastrow) {
					for (int j = firstcell; j <= lastcell; j++) {
						list.get(firstrow)[j] = list.get(firstrow)[j];
					}
				}
				// 处理合并行列
				if (firstcell != lastcell && firstrow != lastrow) {
					for (int j = firstrow; j <= lastrow; j++) {
						for (int k = firstcell; k <= lastcell; k++) {
							list.get(j)[k] = list.get(firstrow)[firstcell];
						}
					}
				}
			}
			listDate = list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值