1. 程式人生 > >Excel匯入匯出-(poi)簡單封裝兩個類,拿來就可以用

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

前言

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

先看一下效果

在這裡插入圖片描述

在這裡插入圖片描述

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

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