Excel匯入匯出-(poi)簡單封裝兩個類,拿來就可以用

藍星花發表於2018-10-04

前言

我們在做專案中,肯定有Excel匯入匯出這個需求,但看網上poi相關文件亂七八糟,還不如干脆實際一點,直接來個稍微簡單點的demo,暫時把業務相關的東西拋開,於是我直接封裝了兩個ExcelExport,ExcelImport類,通過執行main方法,我們就能快速體驗匯入匯出的效果。然後我們用springboot搭建了web專案,體驗一下web匯入excel和匯出excel。

Github專案原始碼 poi-common: https://github.com/chenxingxing6/poi-common


先看一下效果

在這裡插入圖片描述

在這裡插入圖片描述

匯入測試:
在這裡插入圖片描述

web頁面(vue實現的):
在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述


POI常用類說明

類名 作用
HSSFWorkbook Excel的文件物件
HSSFSheet sheet
HSSFRow Excel的行
HSSFCell Excel的格子單元
HSSFFont Excel字型
HSSFCellStyle 格子單元樣式

開始封裝ExportExcel類

 <!-- POI -->
<poi-version>3.15</poi-version>
<dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>${poi-version}</version>
  </dependency>
  <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>${poi-version}</version>
  </dependency>

我們先把思路理清楚:

private SXSSFWorkbook wb; //工作薄物件
private Sheet sheet; //工作表物件
private Map<String, //CellStyle> styles; // 樣式列表
private int rownum; //當前行號
建立標題-> 建立表格head-> 建立單元格,並把值設定進去(excel也是有規律的,遍歷他就好)

package com.example.poi;

import com.example.vo.UserVo;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 匯出Excel檔案(匯出“XLSX”格式,支援大資料量匯出)
 * @author lanxinghua
 * @version 2018-10-03
 */
public class ExportExcel {
	
	private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
			
	/**
	 * 工作薄物件
	 */
	private SXSSFWorkbook wb;
	
	/**
	 * 工作表物件
	 */
	private Sheet sheet;
	
	/**
	 * 樣式列表
	 */
	private Map<String, CellStyle> styles;
	
	/**
	 * 當前行號
	 */
	private int rownum;

	/**
	 * 建構函式
	 * @param title 表格標題,傳“空值”,表示無標題
	 * @param headerList 表頭列表
	 */
	public ExportExcel(String title, List<String> headerList) {
		initialize(title, headerList);
	}

	/**
	 * 初始化函式
	 * @param title 表格標題,傳“空值”,表示無標題
	 * @param headerList 表頭列表
	 */
	private void initialize(String title, List<String> headerList) {
		this.wb = new SXSSFWorkbook(500);
		this.sheet = wb.createSheet("Export");
		this.styles = createStyles(wb);
		// Create title
		if (StringUtils.isNotBlank(title)){
			Row titleRow = sheet.createRow(rownum++);
			titleRow.setHeightInPoints(30);
			Cell titleCell = titleRow.createCell(0);
			titleCell.setCellStyle(styles.get("title"));
			titleCell.setCellValue(title);
			sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
					titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
		}
		// Create header
		if (headerList == null){
			throw new RuntimeException("headerList not null!");
		}
		Row headerRow = sheet.createRow(rownum++);
		headerRow.setHeightInPoints(16);
		for (int i = 0; i < headerList.size(); i++) {
			Cell cell = headerRow.createCell(i);
			cell.setCellStyle(styles.get("header"));
			String[] ss = StringUtils.split(headerList.get(i), "**", 2);
			if (ss.length==2){
				cell.setCellValue(ss[0]);
				Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
						new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
				comment.setString(new XSSFRichTextString(ss[1]));
				cell.setCellComment(comment);
			}else{
				cell.setCellValue(headerList.get(i));
			}
		}
		for (int i = 0; i < headerList.size(); i++) {
			int colWidth = sheet.getColumnWidth(i)*2;
	        sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
		}
		//sheet.setColumnWidth(3,10000);
		log.debug("Initialize success.");
	}
	
	/**
	 * 建立表格樣式
	 * @param wb 工作薄物件
	 * @return 樣式列表
	 */
	private Map<String, CellStyle> createStyles(Workbook wb) {
		Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
		
		CellStyle style = wb.createCellStyle();
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		Font titleFont = wb.createFont();
		titleFont.setFontName("Arial");
		titleFont.setFontHeightInPoints((short) 16);
		titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style.setFont(titleFont);
		styles.put("title", style);

		style = wb.createCellStyle();
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		Font dataFont = wb.createFont();
		dataFont.setFontName("Arial");
		dataFont.setFontHeightInPoints((short) 10);
		style.setFont(dataFont);
		styles.put("data", style);
		
		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_LEFT);
		styles.put("data1", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_CENTER);
		styles.put("data2", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		styles.put("data3", style);
		
		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
//		style.setWrapText(true);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		Font headerFont = wb.createFont();
		headerFont.setFontName("Arial");
		headerFont.setFontHeightInPoints((short) 10);
		headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		headerFont.setColor(IndexedColors.WHITE.getIndex());
		style.setFont(headerFont);
		styles.put("header", style);
		
		return styles;
	}

	/**
	 * 新增一行
	 * @return 行物件
	 */
	public Row addRow(){
		return sheet.createRow(rownum++);
	}
	

	/**
	 * 新增一個單元格
	 * @param row 新增的行
	 * @param column 新增列號
	 * @param val 新增值
	 * @return 單元格物件
	 */
	public Cell addCell(Row row, int column, Object val){
		return this.addCell(row, column, val, 0);
	}


	/**
	 * 新增一個單元格
	 * @param row 新增的行
	 * @param column 新增列號
	 * @param val 新增值
	 * @param align 對齊方式(1:靠左;2:居中;3:靠右)
	 * @return 單元格物件
	 */
	public Cell addCell(Row row, int column, Object val, int align){
		Cell cell = row.createCell(column);
		String cellFormatString = "@";
		try {
			if(val == null){
				cell.setCellValue("");
			}{
				if(val instanceof String) {
					cell.setCellValue((String) val);
				}else if(val instanceof Integer) {
					cell.setCellValue((Integer) val);
					cellFormatString = "0";
				}else if(val instanceof Long) {
					cell.setCellValue((Long) val);
					cellFormatString = "0";
				}else if(val instanceof Double) {
					cell.setCellValue((Double) val);
					cellFormatString = "0.00";
				}else if(val instanceof Float) {
					cell.setCellValue((Float) val);
					cellFormatString = "0.00";
				}else if(val instanceof Date) {
					cell.setCellValue((Date) val);
					cellFormatString = "yyyy-MM-dd HH:mm";
				}
			}
			if (val != null){
				CellStyle style = styles.get("data_column_"+column);
				if (style == null){
					style = wb.createCellStyle();
					style.cloneStyleFrom(styles.get("data"+(align>=1&&align<=3?align:2)));
			        style.setDataFormat(wb.createDataFormat().getFormat(cellFormatString));
					styles.put("data_column_" + column, style);
				}
				cell.setCellStyle(style);
			}
		} catch (Exception ex) {
			log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString());
			cell.setCellValue(val.toString());
		}
		return cell;
	}

	/**
     * 新增資料
	 *
	 * @param dataList
     * @return
     */
	public ExportExcel setDataList(List<UserVo> dataList){
		for (int i = 0; i < dataList.size(); i++) {
			Row row = this.addRow();
			UserVo user = dataList.get(i);
			this.addCell(row, 0, user.getId());
			this.addCell(row, 1, user.getUserName());
			this.addCell(row, 2, user.getAge());
		}
		return this;
	}

	
	/**
	 * 輸出資料流
	 * @param os 輸出資料流
	 */
	public ExportExcel write(OutputStream os) throws IOException{
		wb.write(os);
		return this;
	}
	
	/**
	 * 輸出到客戶端
	 * @param fileName 輸出檔名
	 */
	public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
		response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+fileName);
		write(response.getOutputStream());
		return this;
	}
	
	/**
	 * 輸出到檔案
	 */
	public ExportExcel writeFile(String name) throws Exception{
		FileOutputStream os = new FileOutputStream(name);
		this.write(os);
		return this;
	}
	
	/**
	 * 清理臨時檔案
	 */
	public ExportExcel dispose(){
		wb.dispose();
		return this;
	}
	
	/**
	 * 匯出測試
	 */
	public static void main(String[] args) throws Exception {
		List<String> headerList = Lists.newArrayList();
		headerList.add("編號");
		headerList.add("姓名");
		headerList.add("年齡");
		List<UserVo> dataList = Lists.newArrayList();
		for (int i = 1; i <= headerList.size(); i++) {
			UserVo userVo = new UserVo();
			userVo.setId(String.valueOf(i));
			userVo.setAge("年齡"+i);
			userVo.setUserName("使用者"+i);
			dataList.add(userVo);

		}
		ExportExcel ee = new ExportExcel("表格標題", headerList).setDataList(dataList);
		ee.writeFile("target/export.xlsx");
		ee.dispose();
		log.debug("Export success.");
	}
}

開始封裝ImportExcel類

package com.example.poi;

import com.alibaba.fastjson.JSON;
import com.example.vo.UserVo;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 匯入Excel檔案(支援“XLS”和“XLSX”格式)
 * @author lanxinghua
 * @version 2018-10-03
 */

public class ImportExcel {
	
	private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
			
	/**
	 * 工作薄物件
	 */
	private Workbook wb;
	
	/**
	 * 工作表物件
	 */
	private Sheet sheet;
	
	/**
	 * 標題行號
	 */
	private int headerNum;
	
	/**
	 * 建構函式
	 * @param headerNum 標題行號,資料行號=標題行號+1
	 * @throws InvalidFormatException
	 * @throws IOException 
	 */
	public ImportExcel(String fileName, int headerNum) throws Exception {
		this(new File(fileName), headerNum);
	}
	
	/**
	 * 建構函式
	 * @param headerNum 標題行號,資料行號=標題行號+1
	 * @throws InvalidFormatException
	 * @throws IOException 
	 */
	public ImportExcel(File file, int headerNum) throws Exception {
		this(file, headerNum, 0);
	}

	/**
	 * 建構函式
	 * @param headerNum 標題行號,資料行號=標題行號+1
	 * @param sheetIndex 工作表編號
	 * @throws InvalidFormatException
	 * @throws IOException 
	 */
	public ImportExcel(String fileName, int headerNum, int sheetIndex) throws Exception {
		this(new File(fileName), headerNum, sheetIndex);
	}
	
	/**
	 * 建構函式
	 * @param headerNum 標題行號,資料行號=標題行號+1
	 * @param sheetIndex 工作表編號
	 * @throws InvalidFormatException
	 * @throws IOException 
	 */
	public ImportExcel(File file, int headerNum, int sheetIndex) throws Exception {
		this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
	}
	
	/**
	 * 建構函式
	 * @param headerNum 標題行號,資料行號=標題行號+1
	 * @param sheetIndex 工作表編號
	 * @throws InvalidFormatException
	 * @throws IOException 
	 */
	public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex) throws Exception {
		this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
	}

	/**
	 * 建構函式
	 * @param headerNum 標題行號,資料行號=標題行號+1
	 * @param sheetIndex 工作表編號
	 * @throws InvalidFormatException
	 * @throws IOException 
	 */
	public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex) throws Exception {
		if (StringUtils.isBlank(fileName)){
			throw new Exception("匯入文件為空!");
		}else if(fileName.toLowerCase().endsWith("xls")){    
			this.wb = new HSSFWorkbook(is);
        }else if(fileName.toLowerCase().endsWith("xlsx")){  
        	this.wb = new XSSFWorkbook(is);
        }else{  
        	throw new Exception("文件格式不正確!");
        }  
		if (this.wb.getNumberOfSheets()<sheetIndex){
			throw new Exception("文件中沒有工作表!");
		}
		this.sheet = this.wb.getSheetAt(sheetIndex);
		this.headerNum = headerNum;
		log.debug("Initialize success.");
	}
	
	/**
	 * 獲取行物件
	 * @param rownum
	 * @return
	 */
	public Row getRow(int rownum){
		return this.sheet.getRow(rownum);
	}

	/**
	 * 獲取資料行號
	 * @return
	 */
	public int getDataRowNum(){
		return headerNum+1;
	}
	
	/**
	 * 獲取最後一個資料行號
	 * @return
	 */
	public int getLastDataRowNum(){
		return this.sheet.getLastRowNum()+headerNum;
	}
	
	/**
	 * 獲取最後一個列號
	 * @return
	 */
	public int getLastCellNum(){
		return this.getRow(headerNum).getLastCellNum();
	}
	
	/**
	 * 獲取單元格值
	 * @param row 獲取的行
	 * @param column 獲取單元格列號
	 * @return 單元格值
	 */
	public Object getCellValue(Row row, int column){
		Object val = "";
		try{
			Cell cell = row.getCell(column);
			if (cell != null){
				if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
					val = cell.getNumericCellValue();
				}else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
					val = cell.getStringCellValue();
				}else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
					val = cell.getCellFormula();
				}else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
					val = cell.getBooleanCellValue();
				}else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
					val = cell.getErrorCellValue();
				}
			}
		}catch (Exception e) {
			return val;
		}
		return val;
	}
	
	/**
	 * 獲取匯入資料列表
	 */
	public List<UserVo> getDataList(){
		List<UserVo> dataList = Lists.newArrayList();
		for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
			Row row = this.getRow(i);
			UserVo user = new UserVo();
			user.setId(String.valueOf(this.getCellValue(row, 0)));
			user.setUserName(String.valueOf(this.getCellValue(row, 1)));
			user.setAge(String.valueOf(this.getCellValue(row, 2)));
			dataList.add(user);
		}
		return dataList;
	}

	/**
	 * 匯入測試
	 */
	public static void main(String[] args) throws Throwable {
		String filePath = "target/export.xlsx";
		FileInputStream in = new FileInputStream(filePath);
		XSSFWorkbook wb = new XSSFWorkbook(in);
		System.out.println("sheet個數:"+wb.getNumberOfSheets());
		System.out.println("sheet名字:"+wb.getSheetName(0));
		ImportExcel importExcel = new ImportExcel(filePath, 1);
		List<UserVo> dataList = importExcel.getDataList();
		dataList.forEach(user -> {
			System.out.println(JSON.toJSONString(user));
		});
	}
}

結合Web,進行匯入和匯出

Poicontroller

package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.poi.ExportExcel;
import com.example.poi.ImportExcel;
import com.example.vo.UserVo;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * User: lanxinghua
 * Date: 2018/10/3 17:45
 * Desc:
 */
@Controller
@RequestMapping("/poi")
public class PoiController {
    private static final Logger logger = LoggerFactory.getLogger(PoiController.class);

    /**
     * 跳轉到頁面
     *
     * @return
     */
    @RequestMapping("/view")
    public String view() {
        return "/poi";
    }

    /**
     * 匯出資料
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void exportCard(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String fileName = URLEncoder.encode("商家畫像.xlsx", "utf-8");
            List<String> headerList = Lists.newArrayList();
            headerList.add("編號");
            headerList.add("姓名");
            headerList.add("年齡");
            List<UserVo> data = getData(headerList);
            new ExportExcel("表格標題", headerList).setDataList(data).write(response, fileName).dispose();
            return;
        } catch (Exception e) {
            logger.error("匯出失敗" + e.getMessage());
        }
    }

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ResponseBody
    public String importFile(MultipartFile file) throws Exception {
        Map<String,Object> map = new HashMap<>();
        int successNum = 0;
        int failureNum = 0;
        int totalNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        ImportExcel importExcel = new ImportExcel(file, 1, 0);
        List<UserVo> dataList = importExcel.getDataList();
        totalNum = dataList.size();
        for (UserVo userVo : dataList) {
            logger.info("[資料:]"+JSON.toJSONString(userVo));
            //對資料進行校驗
            if (!"使用者1".equals(userVo.getUserName())) {
                //儲存到資料庫
                //對user進行校驗,以後這部分我們可以用BeanValidarors進行校驗,然後將異常的捕獲,返回給前臺
                successNum++;
            }else {
                failureNum++;
                failureMsg.append("<br/>第"+failureNum+"條,使用者:"+userVo.getUserName()+"已經存在;");

            }
        }
        map.put("successNum", successNum);
        map.put("failureNum", failureNum);
        map.put("totalNum", totalNum);
        map.put("msg", failureMsg);
        return JSON.toJSONString(map);
    }

    /**
     * 獲取模擬資料
     *
     * @return
     */
    @RequestMapping(value = "/data")
    @ResponseBody
    public String getDatas() {
        List<String> headerList = Lists.newArrayList();
        headerList.add("編號");
        headerList.add("姓名");
        headerList.add("年齡");
        List<UserVo> data = getData(headerList);
        return JSON.toJSONString(data);
    }

    /**
     * 假造資料
     *
     * @param headerList
     * @return
     */
    private List<UserVo> getData(List<String> headerList) {
        List<UserVo> dataList = Lists.newArrayList();
        for (int i = 1; i <= headerList.size(); i++) {
            UserVo userVo = new UserVo();
            userVo.setId(String.valueOf(i));
            userVo.setAge("年齡" + i);
            userVo.setUserName("使用者" + i);
            dataList.add(userVo);

        }
        return dataList;
    }
}

總結

如果我們有多個sheet,我們可以用多執行緒,加快響應的時間。我們對匯入的資料可以用BeanValidation進行校驗,然後將錯誤資訊返回給前臺,其實我們可以對Vo的屬性加上註解,然後通過反射,對資料進行處理,這樣的好處就是更加的通用,感興趣的同學可以試一下,自定義匯入匯出的註解。

相關文章