spring boot實現excel上傳解析

controller:

  @RequestMapping(value = "/ImportExcel", method = RequestMethod.POST)
  public JSONObject templateImportExcel(@RequestParam(value = "file", required = true) MultipartFile file) {
    return baseService.templateImportExcel(file);
  }
```java
在這裏插入代碼片

service:

```ja@Service
public class BaseService {

//
//  @Autowired
//  JdbcTemplate jdbcTemplate;
  public JSONObject templateImportExcel(MultipartFile file) {
    String originalFilename = file.getOriginalFilename();
    // 默認從第一行開始讀取
    InputStream is = null;
    Map<String, List<Map<String, Object>>> excel = null;
    try {
      is = file.getInputStream();
      excel = ExcelUtil.parseExcelSheets(is, originalFilename);
      // sheet1
      List<Map<String, Object>> forList = excel.get("key0");
      // sheet2
      List<Map<String, Object>> forList2 = excel.get("key1");



      System.out.println("map"+excel);
    } catch (Exception e) {
      e.printStackTrace();
    }

excel解析工具類:

package com.example.demo.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
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.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;

@Component
public class ExcelUtil {

	private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
	private final static String excel2003L = ".xls"; // 2003- 版本的excel
	private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel

	/**
	 * Float類型數據小數位
	 */
	private String floatDecimal = ".00";
	/**
	 * Double類型數據小數位
	 */
	private String doubleDecimal = ".00";

	private DecimalFormat floatDecimalFormat = new DecimalFormat(floatDecimal);
	/**
	 * The Double decimal format.
	 */
	private DecimalFormat doubleDecimalFormat = new DecimalFormat(doubleDecimal);
	/**
	 * 日期格式化
	 */
	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

	private XSSFWorkbook workbook;

	/**
	 * 將流中的Excel數據轉成List<Map>
	 * 
	 * @param in       輸入流
	 * @param fileName 文件名(判斷Excel版本)
	 * @param mapping  字段名稱映射
	 * @return
	 * @throws Exception
	 */
	public static List<Map<String, Object>> parseExcel(InputStream in, String fileName) throws Exception {
		// 根據文件名來創建Excel工作薄
		Workbook work = getWorkbook(in, fileName);
		if (null == work) {
			throw new Exception("創建Excel工作薄爲空!");
		}
		Sheet sheet = null;
		Row row = null;
		Cell cell = null;
		// 返回數據
		List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();

		// 遍歷Excel中所有的sheet work.getNumberOfSheets();
		for (int i = 0; i < 1; i++) {
			sheet = work.getSheetAt(i);
			if (sheet == null)
				continue;

			// 取第一行標題
			row = sheet.getRow(0);
			String title[] = null;
			if (row != null) {
				title = new String[row.getLastCellNum()];

				for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
					cell = row.getCell(y);
					title[y] = (String) getCellValue(cell);
				}

			} else
				continue;
			log.info(JSON.toJSONString(title));

			// 遍歷當前sheet中的所有行
			for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
				row = sheet.getRow(j);
				Map<String, Object> m = new HashMap<String, Object>();
				// 遍歷所有的列
				for (int y = row.getFirstCellNum(); y < title.length; y++) {
					cell = row.getCell(y);
					String key = title[y];
					// log.info(JSON.toJSONString(key));
					if (null != cell) {
						m.put(key, getCellValue(cell));
					} else {
						m.put(key, null);
					}
				}
				if (CommUtils.isNullMap(m)) {
					ls.add(m);
				}
			}

		}
		work.close();
		return ls;
	}

	/**
	 * 描述:根據文件後綴,自適應上傳文件的版本
	 * 
	 * @param inStr ,fileName
	 * @return
	 * @throws Exception
	 */
	public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
		Workbook wb = null;
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		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;
	}

	/**
	 * 描述:對錶格中數值進行格式化
	 * 
	 * @param cell
	 * @return
	 */
	public static Object getCellValue(Cell cell) {
		Object value = null;
		DecimalFormat df = new DecimalFormat("0.00"); // 格式化number String字符
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
		DecimalFormat df2 = new DecimalFormat("0.00"); // 格式化數字

		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			value = cell.getRichStringCellValue().getString();
			break;
		case Cell.CELL_TYPE_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 = df2.format(cell.getNumericCellValue());
			}
			break;
		case Cell.CELL_TYPE_BOOLEAN:
			value = cell.getBooleanCellValue();
			break;
		case Cell.CELL_TYPE_BLANK:
			value = "";
			break;
//		case HSSFCell.CELL_TYPE_FORMULA: // 公式類型
//			try {
//				value = String.valueOf(cell.getNumericCellValue());
//			} catch (IllegalStateException e) {
//				value = String.valueOf(cell.getRichStringCellValue());
//			}
//			break;
		default:
			break;
		}
		return value;
	}

	/**
	 * 創建workbook工作簿
	 *
	 * @param titles
	 * @param props
	 * @param dataList
	 * @return
	 */
	public void createExcel(String fileName, String[] titles, String[] props, List<Map<String, Object>> dataList,
			String[] titles2, String[] props2, List<Map<String, Object>> dataList2, String[] titles3, String[] props3,
			List<Map<String, Object>> dataList3, HttpServletResponse response) {
		OutputStream out = null;
		try {
			workbook = new XSSFWorkbook();
			// 創建一個Excel的Sheet
			XSSFSheet sheet = workbook.createSheet("sheet1");
			sheet.setDefaultColumnWidth(15);
			// sheet.setColumnWidth(columnIndex, width);
			// 標題行 - 1行
			XSSFRow titleRow = sheet.createRow(0);

			// 把字體應用到當前的樣式
			// 生成一個 表格標題行樣式
			CellStyle style = workbook.createCellStyle();
			style.setAlignment(HorizontalAlignment.CENTER);
			// 生成一個字體
			Font font = workbook.createFont();
			font.setColor(IndexedColors.BLACK.getIndex());
			font.setFontHeightInPoints((short) 12);
			font.setBold(true);
			style.setFont(font);
			for (int i = 0; i < titles.length; i++) {
				XSSFCell cell = titleRow.createCell(i);
				cell.setCellValue(titles[i]);
				cell.setCellStyle(style);
			}
			// 數據行 - n行
			for (int i = 0; i < dataList.size(); i++) {
				Map<String, Object> map = dataList.get(i);
				XSSFRow row = sheet.createRow(i + 1);
				for (int j = 0; j < props.length; j++) {
					XSSFCell cell = row.createCell(j);
					String prop = props[j];
					cell.setCellValue(map.get(prop) == null ? null : map.get(prop).toString());
				}
			}

			// 創建第二個shell
			XSSFSheet sheet2 = workbook.createSheet("sheet2");
			sheet2.setDefaultColumnWidth(15);
			// sheet.setColumnWidth(columnIndex, width);
			// 標題行 - 1行
			XSSFRow titleRow2 = sheet2.createRow(0);

			// 把字體應用到當前的樣式
			// 生成一個 表格標題行樣式
			CellStyle style2 = workbook.createCellStyle();
			style2.setAlignment(HorizontalAlignment.CENTER);
			// 生成一個字體
			Font font2 = workbook.createFont();
			font2.setColor(IndexedColors.BLACK.getIndex());
			font2.setFontHeightInPoints((short) 12);
			font2.setBold(true);
			style2.setFont(font2);
			for (int i = 0; i < titles2.length; i++) {
				XSSFCell cell2 = titleRow2.createCell(i);
				cell2.setCellValue(titles2[i]);
				cell2.setCellStyle(style);
			}
			// 數據行 - n行
			for (int i = 0; i < dataList2.size(); i++) {
				Map<String, Object> map = dataList2.get(i);
				XSSFRow row = sheet2.createRow(i + 1);
				for (int j = 0; j < props2.length; j++) {
					XSSFCell cell = row.createCell(j);
					String prop = props2[j];
					cell.setCellValue(map.get(prop) == null ? null : map.get(prop).toString());
				}
			}
			// 創建第三個shell
			XSSFSheet sheet3 = workbook.createSheet("sheet3");
			sheet3.setDefaultColumnWidth(15);
			// sheet.setColumnWidth(columnIndex, width);
			// 標題行 - 1行
			XSSFRow titleRow3 = sheet3.createRow(0);

			// 把字體應用到當前的樣式
			// 生成一個 表格標題行樣式
			CellStyle style3 = workbook.createCellStyle();
			style3.setAlignment(HorizontalAlignment.CENTER);
			// 生成一個字體
			Font font3 = workbook.createFont();
			font3.setColor(IndexedColors.BLACK.getIndex());
			font3.setFontHeightInPoints((short) 12);
			font3.setBold(true);
			style3.setFont(font3);
			for (int i = 0; i < titles3.length; i++) {
				XSSFCell cell3 = titleRow3.createCell(i);
				cell3.setCellValue(titles3[i]);
				cell3.setCellStyle(style);
			}
			// 數據行 - n行
			for (int i = 0; i < dataList3.size(); i++) {
				Map<String, Object> map = dataList3.get(i);
				XSSFRow row = sheet3.createRow(i + 1);
				for (int j = 0; j < props3.length; j++) {
					XSSFCell cell = row.createCell(j);
					String prop = props3[j];
					cell.setCellValue(map.get(prop) == null ? null : map.get(prop).toString());
				}
			}

			// 導出文件
			fileName = generateFileName(fileName);
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			out = response.getOutputStream();
			workbook.write(out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(workbook);
		}
	}

	private String generateFileName(String fileName) {
		if (StringUtils.isEmpty(fileName)) {
			fileName = System.currentTimeMillis() + "";
		}
		return fileName += ".xlsx";
	}

	/**
	 * 將流中的Excel數據轉成List<Map>
	 * 
	 * @param in       輸入流
	 * @param fileName 文件名(判斷Excel版本)
	 * @param mapping  字段名稱映射
	 * @return
	 * @throws Exception
	 */
	public static Map<String, List<Map<String, Object>>> parseExcelSheets(InputStream in, String fileName)
			throws Exception {
		// 根據文件名來創建Excel工作薄
		Workbook work = getWorkbook(in, fileName);
		if (null == work) {
			throw new Exception("創建Excel工作薄爲空!");
		}
		Sheet sheet = null;
		Row row = null;
		Cell cell = null;
		Map<String, List<Map<String, Object>>> res = new HashMap<String, List<Map<String, Object>>>();
		// 返回數據
		List<Map<String, Object>> ls = null;

		int sheets = work.getNumberOfSheets();
		for (int i = 0; i < sheets; i++) {
			ls = new ArrayList<Map<String, Object>>();
			sheet = work.getSheetAt(i);
			if (sheet == null)
				continue;

			// 取第一行標題
			row = sheet.getRow(0);
			String title[] = null;
			if (row != null) {
				title = new String[row.getLastCellNum()];

				for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
					cell = row.getCell(y);
					title[y] = (String) getCellValue(cell);
				}

			} else
				continue;
			log.info(JSON.toJSONString(title));

			// 遍歷當前sheet中的所有行
			for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
				row = sheet.getRow(j);
				Map<String, Object> m = new HashMap<String, Object>();
				// 遍歷所有的列
				for (int y = row.getFirstCellNum(); y < title.length; y++) {
					cell = row.getCell(y);
					String key = title[y];
					// log.info(JSON.toJSONString(key));
					if (null != cell) {
						m.put(key, getCellValue(cell));
					} else {
						m.put(key, null);
					}
				}
				if (CommUtils.isNullMap(m)) {
					ls.add(m);
				}
			}
			res.put("key" + i, ls);

		}
		work.close();
		return res;
	}


	/**
	 * 創建workbook工作簿
	 *
	 * @param titles
	 * @param props
	 * @param dataList
	 * @return
	 */
	public void createExcel(String fileName, String[] titles, String[] props, List dataList,
							HttpServletResponse response) {
		OutputStream out = null;
		try {
			workbook = new XSSFWorkbook();
			// 創建一個Excel的Sheet
			XSSFSheet sheet = workbook.createSheet("sheet1");
			sheet.setDefaultColumnWidth(15);
			// sheet.setColumnWidth(columnIndex, width);
			// 標題行 - 1行
			XSSFRow titleRow = sheet.createRow(0);
			CellStyle style = workbook.createCellStyle();
			style.setAlignment(HorizontalAlignment.CENTER);
			// 生成一個字體
			Font font = workbook.createFont();
			font.setColor(IndexedColors.BLACK.getIndex());
			font.setFontHeightInPoints((short) 12);
			font.setBold(true);
			style.setFont(font);
			for (int i = 0; i < titles.length; i++) {
				XSSFCell cell = titleRow.createCell(i);
				cell.setCellValue(titles[i]);
				cell.setCellStyle(style);
			}
			// 數據行 - n行
			for (int i = 0; i < dataList.size(); i++) {
				Object obj = dataList.get(i);
				Class clazz = obj.getClass();
				XSSFRow row = sheet.createRow(i + 1);
				for (int j = 0; j < props.length; j++) {
					XSSFCell cell = row.createCell(j);
					String prop = props[j];
					String methodName = "get" + Character.toUpperCase(prop.charAt(0)) + prop.substring(1);
					Method method = clazz.getDeclaredMethod(methodName);
					// 獲取返回類型
					String returnType = method.getReturnType().getName();
					Object data = method.invoke(obj);
					if (data != null && !"".equals(data)) {
						if ("int".equals(returnType)) {
							cell.setCellValue(Integer.parseInt(data.toString()));
						} else if ("long".equals(returnType)) {
							cell.setCellValue(Long.parseLong(data.toString()));
						} else if ("float".equals(returnType)) {
							cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data.toString())));
						} else if ("double".equals(returnType)) {
							cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data.toString())));
						} else if ("java.util.Date".equals(returnType)) {
							cell.setCellValue(simpleDateFormat.format((Date) data));
						} else {
							cell.setCellValue(data.toString());
						}
					}
				}
			}

			// 導出文件
			fileName = generateFileName(fileName);
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

			out = response.getOutputStream();
			workbook.write(out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(workbook);
		}
	}
}

map是否爲空:

public class CommUtils {

  /**
   * 判斷map是否爲空,爲空返回false
   *
   * @param map
   * @return
   */
  public static boolean isNullMap(Map<String, Object> map) {
    if (null == map) {
      return false;
    }
    Set<String> keySet = map.keySet();

    for (String key : keySet) {
      if (!StringUtils.isEmpty(map.get(key).toString())) {
        return true;
      }
    }
    return false;
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章