ExcelUtils.java 8.4 KB
Newer Older
licc's avatar
licc committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
package cn.wisenergy.common.utils;


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExcelUtils {


	private static final String EXTENSION_XLS = "xls";
	private static final String EXTENSION_XLSX = "xlsx";


	/**
	 * 判断EXCEL版本
	 *
	 * @param in
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static Workbook getWorkbook(InputStream in, String filename) throws IOException {
		Workbook wb = null;
		if (filename.endsWith(EXTENSION_XLS)) {
			wb = new HSSFWorkbook(in);//Excel 2003
		} else if (filename.endsWith(EXTENSION_XLSX)) {
			wb = new XSSFWorkbook(in);//Excel 2007
		}
		return wb;
	}


	/**
	 * 文件校验是否是excel
	 *
	 * @param filePath
	 * @throws FileNotFoundException
	 * @throws FileFormatException
	 */
	public static void preReadCheck(String fileName) throws FileNotFoundException,
			FileFormatException {
		// 常规检查
		if (StringUtils.isBlank(fileName)) {
			throw new FileNotFoundException("传入的文件不存在:" + fileName);
		}

		if (!fileName.endsWith(EXTENSION_XLS) && !fileName.endsWith(EXTENSION_XLSX)) {
			throw new FileFormatException("传入的文件不是excel");
		}
	}


	/**
	 * 读取EXCEL
	 *
	 * @param filePath
	 * @throws FileNotFoundException
	 * @throws FileFormatException
	 */
	public static List<List<String>> readExcel(MultipartFile file) throws FileNotFoundException, FileFormatException {
		// 检查
		preReadCheck(file.getOriginalFilename());
		// 获取workbook对象
		Workbook workbook = null;
		/*InputStream is = new FileInputStream(filePath);*/
		List<List<String>> result = new ArrayList<List<String>>();
		try {
			workbook = getWorkbook(file.getInputStream(), file.getOriginalFilename());
			// workbook = WorkbookFactory.create(is);

			int sheetCount = workbook.getNumberOfSheets();  //Sheet的数量
			// 读文件 一个sheet一个sheet地读取
			for (int numSheet = 0; numSheet < sheetCount; numSheet++) {
				Sheet sheet = workbook.getSheetAt(numSheet);
				if (sheet == null) {
					continue;
				}

				int firstRowIndex = sheet.getFirstRowNum();
				int lastRowIndex = sheet.getLastRowNum();

				if (firstRowIndex != lastRowIndex && lastRowIndex != 0) {

					// 读取数据行
					for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
						Row currentRow = sheet.getRow(rowIndex);// 当前行
						int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
						int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
						List<String> rowList = new ArrayList<String>();
						for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
							Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格

							String currentCellValue = getCellValue(currentCell, true);// 当前单元格的值
							rowList.add(currentCellValue);
						}

						//行为空的不读
						Boolean flag = false;
						for (String str : rowList) {
							if (!StringUtils.isBlank(str)) {
								flag = true;
								break;
							}
						}
						if (flag) {
							result.add(rowList);
						}
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return result;
	}

	public static List<List<String>> readInlandCompare(String filePath, Integer startSheet, Integer endSheet) throws FileNotFoundException, FileFormatException {
		// 检查
		preReadCheck(filePath);
		// 获取workbook对象
		Workbook workbook = null;
		InputStream is = new FileInputStream(filePath);
		List<List<String>> result = new ArrayList<List<String>>();
		try {
			workbook = getWorkbook(is, filePath);
			// workbook = WorkbookFactory.create(is);

			int sheetCount = workbook.getNumberOfSheets();  //Sheet的数量
			// 读文件 一个sheet一个sheet地读取
			for (int numSheet = startSheet; numSheet < endSheet; numSheet++) {
				Sheet sheet = workbook.getSheetAt(numSheet);
				if (sheet == null) {
					continue;
				}

				int firstRowIndex = sheet.getFirstRowNum();
				int lastRowIndex = sheet.getLastRowNum();

				if (firstRowIndex != lastRowIndex && lastRowIndex != 0) {

					// 读取数据行
					for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
						Row currentRow = sheet.getRow(rowIndex);// 当前行
						int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
						int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
						List<String> rowList = new ArrayList<String>();
						for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
							Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格

							String currentCellValue = getCellValue(currentCell, true);// 当前单元格的值
							rowList.add(currentCellValue);
						}
						//行为空的不读
						Boolean flag = false;
						for (String str : rowList) {
							if (!StringUtils.isBlank(str)) {
								flag = true;
								break;
							}
						}
						if (flag) {
							result.add(rowList);
						}
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return result;
	}

	/**
	 * 取单元格的值
	 *
	 * @param cell       单元格对象
	 * @param treatAsStr 为true时,当做文本来取值 (取到的是文本,不会把“1”取成“1.0”)
	 * @return
	 */
	public static String getCellValue(Cell cell, boolean treatAsStr) {
		if (cell == null) {
			return "";
		}

       /* if (treatAsStr) {
            // 虽然excel中设置的都是文本,但是数字文本还被读错,如“1”取成“1.0”
            // 加上下面这句,临时把它当做文本来读取
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }*/
		//SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");

		String cellValue = null;
		int cellType = cell.getCellType();
		switch (cellType) {
			case Cell.CELL_TYPE_STRING: // 文本
				cellValue = cell.getStringCellValue();
				break;
			case Cell.CELL_TYPE_NUMERIC: // 数字、日期
				if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
					SimpleDateFormat sdf = null;
					if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
							.getBuiltinFormat("h:mm")) {
						sdf = new SimpleDateFormat("HH:mm:ss");
					} else {// 日期
						sdf = new SimpleDateFormat("yyyy-MM-dd");
					}
					Date date = cell.getDateCellValue();
					return sdf.format(date);
				} else if (cell.getCellStyle().getDataFormat() == 58) {
					// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					double value = cell.getNumericCellValue();
					Date date = org.apache.poi.ss.usermodel.DateUtil
							.getJavaDate(value);
					return sdf.format(date);
				} else {
					double value = cell.getNumericCellValue();
					CellStyle style = cell.getCellStyle();
					DecimalFormat format = new DecimalFormat();
					String temp = style.getDataFormatString();
					// 单元格设置成常规
					if (temp.equals("General")) {
						format.applyPattern("#");
					}
					return format.format(value);
				}

			case Cell.CELL_TYPE_BOOLEAN: // 布尔型
				cellValue = String.valueOf(cell.getBooleanCellValue());
				break;
			case Cell.CELL_TYPE_BLANK: // 空白
				cellValue = cell.getStringCellValue();
				break;
			case Cell.CELL_TYPE_ERROR: // 错误
				cellValue = "错误";
				break;
			case Cell.CELL_TYPE_FORMULA: // 公式
               /* try {
                    cellValue = cell.getStringCellValue();
                } catch (IllegalStateException e) {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                }*/
				try {
					cellValue = String.valueOf(cell.getNumericCellValue());
				} catch (IllegalStateException e) {
					cellValue = String.valueOf(cell.getRichStringCellValue());
				}
				break;
			default:
				cellValue = "错误";
		}
		return cellValue;
	}


}