POI操作Excel小结

来源:互联网 发布:手机如何网络翻墙 编辑:程序博客网 时间:2024/06/08 15:24
package com.cn.shoje.oa.modules.util;import java.io.IOException;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.poi.hssf.usermodel.HSSFDateUtil;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class ExcelUtil {public static Map<Integer, List<String>> readExcel(InputStream is) throws IOException {List<String> list = null;Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();XSSFWorkbook book = new XSSFWorkbook(is);XSSFSheet sheet = book.getSheetAt(0);Iterator<Row> rowList = sheet.rowIterator();while (rowList.hasNext()) {// 遍历行Row row = rowList.next();list = new ArrayList<String>();if (row.getRowNum() == 0) {continue;} else {Iterator<Cell> cellList = row.cellIterator();while (cellList.hasNext()) {// 遍历单元格String cell_value = "";Cell cell = cellList.next();switch (cell.getCellType()) {case 1: {cell_value = cell.getStringCellValue();break;}case 0: {if (HSSFDateUtil.isCellDateFormatted(cell)) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");cell_value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();} else {cell_value = String.valueOf((int)cell.getNumericCellValue());//这里要及其注意,单元格数字默认是double!}break;}}list.add(cell_value);}System.out.println(list.toString());map.put(row.getRowNum(), list);// 存储每一行的数据,Key为行号,0开始下标}}is.close();return map;}}

1 0
原创粉丝点击