栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA使用apache.poi导入excel文档

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA使用apache.poi导入excel文档

文章目录
  • 依赖
  • 一、excel导入工具类
  • 二、调用工具类


依赖
		
            org.apache.poi
            poi-ooxml
            3.17
        

一、excel导入工具类

importExcelUtil.java

package com.print.utils;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;




public class importExcelUtil {
	private final static String excel2003L = ".xls"; // 2003- 版本的excel
	private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel
	
	public List> getBankListByExcel(InputStream in, String fileName) throws Exception {
		List> list = null;

		// 创建Excel工作薄
		Workbook work = this.getWorkbook(in, fileName);
		if (null == work) {
			throw new Exception("创建Excel工作薄为空!");
		}
		Sheet sheet = null;
		Row row = null;
		Cell cell = null;

		list = new ArrayList>();
		// 遍历Excel中所有的sheet
		for (int i = 0; i < work.getNumberOfSheets(); i++) {
			sheet = work.getSheetAt(i);
			if (sheet == null) {
				continue;
			}
			//获得最长列宽
			int length = 0;
			for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum() + 1; j++) { // 这里的加一是因为下面的循环跳过取第一行表头的数据内容了
				row = sheet.getRow(j);
				if (row == null || row.getFirstCellNum() == j) {
					continue;
				}
				if(row.getLastCellNum() > length){
					length = row.getLastCellNum();
				}

			}
			// 遍历当前sheet中的所有行
			for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum() + 1; j++) { // 这里的加一是因为下面的循环跳过取第一行表头的数据内容了
				row = sheet.getRow(j);
				if (row == null || row.getFirstCellNum() == j) {
					continue;
				}
				// 遍历所有的列
				List li = new ArrayList();
				for (int y = row.getFirstCellNum(); y < length; y++) {
					cell = row.getCell(y);
					li.add(this.getCellValue(cell));
				}
				list.add(li);
			}
		}
		in.close();
		return list;
	}
	
	public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
		Workbook wb = null;
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		fileType = fileType.toLowerCase();
		if (excel2003L.equals(fileType)) {	
			wb = new HSSFWorkbook(inStr); // 2003-
		} else if (excel2007U.equals(fileType)) {
			wb = new XSSFWorkbook(inStr); // 2007+
		} else {
			throw new Exception("解析的文件格式有误!");
		}
		return wb;
	}
	
	public static String getCellValue(Cell cell) {
		String value = "";
		DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
		DecimalFormat df2 = new DecimalFormat(""); // 格式化数字
		if(cell == null){
			value = "";
			return value;
		}
		switch (cell.getCellTypeEnum()) {
		case STRING:
			value = cell.getRichStringCellValue().getString();
			break;
		case NUMERIC:
			if ("General".equals(cell.getCellStyle().getDataFormatString())) {
				value = df.format(cell.getNumericCellValue());
			} else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
				value = sdf.format(cell.getDateCellValue());
			} else {
				value = df.format(cell.getNumericCellValue());
				//value = cell.getNumericCellValue();
			}
			break;
		case BOOLEAN:
			value =Boolean.toString(cell.getBooleanCellValue());
			break;
		case BLANK:
			value = "";
			break;
		default:
			break;
		}
		return value;
	}
	//读取excel的内容 键值对形式
	public static List> readExcelKeyVelue(MultipartFile excelFile) throws Exception{
		List> list = new ArrayList>();
		InputStream in= excelFile.getInputStream();
		// 创建Excel工作薄
		Workbook workbook = getWorkbook(in, excelFile.getOriginalFilename());
		if (null == workbook) {
			throw new Exception("创建Excel工作薄为空!");
		}
		Sheet s = null;
		//excel的内容从0开始 0即为第一行
		int heardRowIndex=0;//表头所在行
		int starRow=1;//内容开始读取去行
		//遍历所有sheet
		for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
			s = workbook.getSheetAt(numSheet);//第i个sheet
			if (s == null) {
				continue;
			}
			int totalRows = s.getLastRowNum();//行数
			//读取表头
			List headers = readExcelHeader(s, heardRowIndex);
			//遍历所有行
			for (int i = starRow; i <= totalRows; i++) {
				Row row = s.getRow(i);//取第几行
				if (row != null) {
					Map rowMap = new HashMap(headers.size());
					//遍历列
					for (int k = 0; k < headers.size(); k++) {
						//key:上面方法取一行,value:字段
						if(getCellValue(row.getCell(k))==null){
							rowMap.put(headers.get(k), getCellValue(row.getCell(k)));
						}else{
							rowMap.put(headers.get(k), getCellValue(row.getCell(k)).trim());
						}
					}
					list.add(rowMap);
				}
			}
		}
		return list;
	}
	
	public static List readExcelHeader(Sheet sheet, int rows) throws IOException {
		Row row = sheet.getRow(rows);
		if (row == null) {
			return null;
		}
		// 标题总列数
		int colNum = row.getPhysicalNumberOfCells();
		List list = new ArrayList();
		for (int i = 0; i < colNum; i++) {
			String s=getCellValue(row.getCell(i));
			if(s==null){
				list.add(s);
			}else{
				list.add(s.trim());
			}
		}
		return list;
	}
}
 
二、调用工具类 
	@PostMapping("importExcel")
	@ResponseBody
	public List> importExcel(MultipartFile file){
		try {
			//excel表头作为key,以List>结构返回
			//如:[{"表头1=内容1","表头2"="内容2"}]
			List> readExcelKeyVelue = importExcelUtil.readExcelKeyVelue(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return arrayList;
	}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号