POI导出合并列头excel

一:定义列头合并工具类

/**
 * 
 */
package com.faf.gf.ebank.fp.util;

import java.util.List;

/**
 * @author zfc
 * @date 2019年11月12日 下午2:07:51  
 */
public class Header {
	private String name;//列名
	private int cellCol;//单元格列
	private int cellRow;//单元格行
	private int startRow;//起始行
	private int endRow;//结束行
	private int startCol;//起始列
	private int endCol;//结束列

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the cellCol
	 */
	public int getCellCol() {
		return cellCol;
	}
	/**
	 * @param cellCol the cellCol to set
	 */
	public void setCellCol(int cellCol) {
		this.cellCol = cellCol;
	}
	/**
	 * @return the cellRow
	 */
	public int getCellRow() {
		return cellRow;
	}
	/**
	 * @param cellRow the cellRow to set
	 */
	public void setCellRow(int cellRow) {
		this.cellRow = cellRow;
	}
	/**
	 * @return the startRow
	 */
	public int getStartRow() {
		return startRow;
	}
	/**
	 * @param startRow the startRow to set
	 */
	public void setStartRow(int startRow) {
		this.startRow = startRow;
	}
	/**
	 * @return the endRow
	 */
	public int getEndRow() {
		return endRow;
	}
	/**
	 * @param endRow the endRow to set
	 */
	public void setEndRow(int endRow) {
		this.endRow = endRow;
	}
	/**
	 * @return the startCol
	 */
	public int getStartCol() {
		return startCol;
	}
	/**
	 * @param startCol the startCol to set
	 */
	public void setStartCol(int startCol) {
		this.startCol = startCol;
	}
	/**
	 * @return the endCol
	 */
	public int getEndCol() {
		return endCol;
	}
	/**
	 * @param endCol the endCol to set
	 */
	public void setEndCol(int endCol) {
		this.endCol = endCol;
	}

	/**
	 * 
	 * @param headers
	 * @param name  列名
	 * @param cellCol  单元格列
	 * @param cellRow  单元格行
	 * @param startRow 起始行
	 * @param endRow 结束行
	 * @param startCol 起始列
	 * @param endCol 结束列
	 * @return
	 * 
	 * @author zfc
	 * @date 2019年11月12日 下午2:17:31
	 */
	public static List<Header> setList(List<Header> headers ,String name ,int cellCol , int cellRow , int startRow , int endRow , int startCol , int endCol) {
		Header header = new Header();
		header.setName(name);
		header.setCellCol(cellCol);
		header.setCellRow(cellRow);
		header.setStartRow(startRow);
		header.setEndRow(endRow);
		header.setStartCol(startCol);
		header.setEndCol(endCol);
		headers.add(header);
		return headers;
	}
}

二:POI导出工具类

/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.faf.gf.ebank.fp.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Font;
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.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
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 com.faf.gf.ebank.sys.entity.SubordRelationData;
import com.google.common.collect.Lists;
import com.yqjr.base.framework.utils.Encodes;

/**
 * 导出Excel文件(导出“XLSX”格式,支持大数据量导出   @see org.apache.poi.ss.SpreadsheetVersion)
 * @author ZFC
 * @version 2019-09-09
 */
public class PaymentInstrPlanExportExcel {
	
	private static Logger log = LoggerFactory.getLogger(PaymentInstrPlanExportExcel.class);
			
	/**
	 * 工作薄对象
	 */
	private SXSSFWorkbook wb;
	
	/**
	 * 工作表对象
	 */
	private Sheet sheet;
	
	/**
	 * 样式列表
	 */
	private Map<String, CellStyle> styles;
	
	/**
	 * 当前行号
	 */
	private int rownum;
	
	/**
	 * 注解列表(Object[]{ ExcelField, Field/Method })
	 */
	List<Object[]> annotationList = Lists.newArrayList();
	
	List<Header> headerList;
	
	/**
	 * 构造函数
	 * @param title 表格标题,传“空值”,表示无标题
	 * @param headerList 表头列表
	 */
	public PaymentInstrPlanExportExcel(String title, int rownum, List<Header> headerList) {
		this.headerList = headerList;
		this.rownum = rownum;
		initialize(title, headerList);
	}
	
	/**
	 * 初始化函数
	 * @param title 表格标题,传“空值”,表示无标题
	 * @param headerList 表头列表
	 */
	private void initialize(String title, List<Header> headerList) {
		this.wb = new SXSSFWorkbook(500);
		this.sheet = wb.createSheet("Export");
		this.styles = createStyles(wb);
		// Create header
		if (headerList == null){
			throw new RuntimeException("headerList not null!");
		}
		int row = 0;
		int col = 0;
		for(Header header : headerList){
			CellRangeAddress region = new CellRangeAddress(header.getStartRow(), header.getEndRow(), header.getStartCol(), header.getEndCol());
	        sheet.addMergedRegion(region);
	        setBorderStyle(sheet, region, wb);
	        if(row < header.getEndRow()){//计算列头行数
	        	row = header.getEndRow();
	        }
	        if(col < header.getEndCol()){//计算列头列数
	        	col = header.getEndCol();
	        }
		}
		for (int j = 0; j <= row; j++) {
			Row headerRow = sheet.createRow(rownum++);
			headerRow.setHeightInPoints(16);
			for (int k = 0; k <= col; k++) {
				
				for (Header header : headerList) {
					if(header.getStartCol() <= k && header.getEndCol() >= k && header.getCellRow() == j && header.getStartRow() <=  rownum){ //列合并中
						addTitleCol(headerRow, k, header);
					}
					if(header.getStartRow() <=  j && header.getEndRow() >=  j && header.getStartCol() >= k && header.getEndCol() <= k){
						addTitleCol(headerRow, k, header);
					}

				}
			}
        }
		log.debug("Initialize success.");
	}
	
	/**
	 * 列头单元格
	 * @param title 表格标题,传“空值”,表示无标题
	 * @param headerList 表头列表
	 */
	private void addTitleCol(Row headerRow, int k , Header header) {
		Cell cell = headerRow.createCell(k);
		cell.setCellStyle(styles.get("header"));
		String[] ss = StringUtils.split(header.getName(), "**", 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(header.getName());
		}
	}
	
	/**
	 * 创建表格样式
	 * @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_DASHED);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_DASHED);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_DASHED);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_DASHED);
		style.setBottomBorderColor(IndexedColors.BLACK.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_25_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;
	}

	 /**
     * 设置合并单元格边框 - 线条
     * */
    private static void setBorderStyle(Sheet sheet, CellRangeAddress region , Workbook wb) {
        // 合并单元格左边框样式
        RegionUtil.setBorderLeft(CellStyle.BORDER_DASHED, region, sheet, wb);
        RegionUtil.setLeftBorderColor(IndexedColors.BLUE.getIndex(), region, sheet, wb);

        // 合并单元格上边框样式
        RegionUtil.setBorderTop(CellStyle.BORDER_DASHED, region, sheet, wb);
        RegionUtil.setTopBorderColor(IndexedColors.BLUE.getIndex(), region, sheet, wb);

        // 合并单元格右边框样式
        RegionUtil.setBorderRight(CellStyle.BORDER_DASHED, region, sheet, wb);
        RegionUtil.setRightBorderColor(IndexedColors.BLUE.getIndex(), region, sheet, wb);

        // 合并单元格下边框样式
        RegionUtil.setBorderBottom(CellStyle.BORDER_DASHED, region, sheet, wb);
        RegionUtil.setBottomBorderColor(IndexedColors.BLUE.getIndex(), region, sheet, wb);
    }
    
	/**
	 * 添加一行
	 * @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, Class.class);
	}
	
	/**
	 * 添加一个单元格
	 * @param row 添加的行
	 * @param column 添加列号
	 * @param val 添加值
	 * @param align 对齐方式(1:靠左;2:居中;3:靠右)
	 * @return 单元格对象
	 */
	public Cell addCell(Row row, int column, Object val , int align){
		return this.addCell(row, column, val, align, Class.class);
	}
	
	/**
	 * 添加一个单元格
	 * @param row 添加的行
	 * @param column 添加列号
	 * @param val 添加值
	 * @param align 对齐方式(1:靠左;2:居中;3:靠右)
	 * @return 单元格对象
	 */
	public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){
		Cell cell = row.createCell(column);
		CellStyle style = styles.get("data"+(align>=1&&align<=3?align:""));
		try {
			if (val == null){
				cell.setCellValue("");
			} else if (val instanceof String) {
				cell.setCellValue((String) val);
			} else if (val instanceof Integer) {
				cell.setCellValue(val.toString());
			} else if (val instanceof Long) {
				cell.setCellValue((Long) val);
			} else if (val instanceof Double || val instanceof BigDecimal) {
				Object obj=val;
//				cell.setCellValue(Double.valueOf(val.toString()));
				cell.setCellValue(Double.parseDouble(val.toString()));// 是数字当作double处理
				style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));//excel 自定义的格式
				cell.setCellStyle(style);
			} else if (val instanceof Float) {
				cell.setCellValue((Float) val);
			} else if (val instanceof Date) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
//				DataFormat format = wb.createDataFormat();
//	            style.setDataFormat(format.getFormat("yyyy-MM-dd"));
				cell.setCellValue(format.format(val));
			} else {
				if (fieldType != Class.class){
					cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
				}else{
					cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(), 
						"fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
				}
			}
		} catch (Exception ex) {
			log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString());
			cell.setCellValue(val.toString());
		}
		cell.setCellStyle(style);
		return cell;
	}
	
	/**
	 * 输出数据流
	 * @param os 输出数据流
	 */
	public PaymentInstrPlanExportExcel write(OutputStream os) throws IOException{
		wb.write(os);
		return this;
	}
	
	/**
	 * 输出到客户端
	 * @param fileName 输出文件名
	 */
	public PaymentInstrPlanExportExcel write(HttpServletResponse response, String fileName) throws IOException{
		for (int i = 0; i < headerList.size(); i++) {  
			sheet.autoSizeColumn(i);
			int colWidth = sheet.getColumnWidth(i) * 17 / 10;
			sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
		}
		response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
		write(response.getOutputStream());
		return this;
	}
	
	/**
	 * 输出到文件
	 * @param fileName 输出文件名
	 */
	public PaymentInstrPlanExportExcel writeFile(String name) throws FileNotFoundException, IOException{
		FileOutputStream os = new FileOutputStream(name);
		this.write(os);
		return this;
	}
	
	/**
	 * 清理临时文件
	 */
	public PaymentInstrPlanExportExcel dispose(){
		wb.dispose();
		return this;
	}
	private static void setRegionBorder(int border, CellRangeAddress region, Sheet sheet,Workbook wb){  
        RegionUtil.setBorderBottom(border,region, sheet, wb);  
        RegionUtil.setBorderLeft(border,region, sheet, wb);  
        RegionUtil.setBorderRight(border,region, sheet, wb);  
        RegionUtil.setBorderTop(border,region, sheet, wb);  
      
    }
	
	/**
	 * 统计导出
	 * @return SearchStatisticsExportExcel 
	 */
	public PaymentInstrPlanExportExcel setDetailList(List<SubordRelationData> bizFxSpotFlat) {
		int i = 0;
		for(SubordRelationData bfsf : bizFxSpotFlat) {
			Row detailRow = this.addRow();
			setDetailCellValue(bfsf, detailRow, i + 1);
			i++;
		}
		return this;
	}
	
	/**
	 * 设置统计详细数据
	 * @param bizFxSpotFlat
	 * @param detailRow
	 */
	public void setDetailCellValue(SubordRelationData finPlan, Row detailRow, int i) {
		java.text.NumberFormat NF = java.text.NumberFormat.getInstance();
		NF.setGroupingUsed(false);//去掉科学计数法显示
		this.addCell(detailRow,0, i);// 序号
		this.addCell(detailRow,1, finPlan.getClientName());// 客户名
	}
}

三:调用导出工具类

/**
	 * 导出即期外汇买卖业务查询列表
	 * 
	 * @throws IOException
	 * @author zhoufance
	 * 
	 */
	@RequestMapping(value = "exportFawPlanApply")
	public String exportFxSpotByWbFile(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		String fileName = "统计导入模板" + DateUtils.getDate("yyyyMMddhhmmss") + ".xlsx";
		List<Header> headerList = Lists.newArrayList();
		headerList = Header.setList(headerList, "序号", 0, 1, 0, 2, 0, 0);
		headerList = Header.setList(headerList, "单位", 1, 1, 0, 2, 1, 1);
		headerList = Header.setList(headerList, "统计列1", 2,1, 0, 2, 2, 2);
		headerList = Header.setList(headerList, "统计列2", 3, 1, 0, 2, 3, 3);
		headerList = Header.setList(headerList, "统计列3" , 4, 0, 0, 0, 4, 4);
		headerList = Header.setList(headerList, "统计列4" , 4, 2, 1, 2, 4, 4);

		headerList = Header.setList(headerList, "统计列5", 5, 1, 0, 2, 5, 5);
		sonJ++;
		headerList = Header.setList(headerList, "统计列6", 6, 1, 0, 2, 6, 6);
		
		SubordRelationData srd2 = new SubordRelationData();
		srd2.setClientCode(UserUtils.getUser().getClientCode());
		srd2.setTransferPricing(1);
		List<SubordRelationData> codelistDatas = subordRelationDataService.findClientAbbreviation(srd2);
		
		try {
			new PaymentInstrPlanExportExcel("统计导入模板", 0, headerList).setDetailList(codelistDatas).write(response, fileName).dispose();
		} catch (IOException e) {
			logger.error("统计导入模板: exception " , e);
		}
		return null;
	}

导出模板结束
导入:
一:导入工具类

/**
 * 
 */
package com.faf.gf.ebank.fp.util;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.springframework.web.multipart.MultipartFile;

/**
 * @author zfc
 * @date 2019年11月13日 下午3:54:15  
 */
public class ExcelRead {
	
	public static final String POINT = ".";
	public static SimpleDateFormat sdf =   new SimpleDateFormat("yyyy/MM/dd");
	public static int totalRows; //sheet中总行数  
    public static int totalCells; //每一行总单元格数  
    private int startRow;//起始行
	private int endRow;//结束行
    /** 
     * read the Excel .xlsx,.xls 
     * @param file jsp中的上传文件 
     * @param startRow;//起始行
     * @param endRow;//结束行
     * @return 
     * @throws IOException  
     */  
    public static List<ArrayList<String>> readExcel(MultipartFile file , int startRow , int endRow) throws IOException {  
                    return readXlsx(file , startRow , endRow);  

    }  
    /** 
     * read the Excel 2010 .xlsx 
     * @param file
     * @return 
     * @throws IOException  
     */  
    public static List<ArrayList<String>> readXlsx(MultipartFile file , int startRow , int endRow){  
        List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();  
        // IO流读取文件  
        InputStream input = null;  
        XSSFWorkbook wb = null;  
        ArrayList<String> rowList = null;  
        try {  
            input = file.getInputStream();  
            // 创建文档  
            wb = new XSSFWorkbook(input);                         
            //读取sheet(页)  
            for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){  
                XSSFSheet xssfSheet = wb.getSheetAt(numSheet);  
                if(xssfSheet == null){  
                    continue;  
                }  
                if(endRow != 0){
                	totalRows = endRow;                
                }else{
                	totalRows = xssfSheet.getLastRowNum();                
                }
                //读取Row,从第三行开始
                for(int rowNum = startRow;rowNum <= totalRows;rowNum++){
                    XSSFRow xssfRow = xssfSheet.getRow(rowNum);  
                    if(xssfRow!=null){  
                        rowList = new ArrayList<String>();  
                        totalCells = xssfRow.getLastCellNum();  
                        //读取列,从第一列开始  
                        for(int c=0;c<totalCells;c++){  
                            XSSFCell cell = xssfRow.getCell(c);  
                            if(cell==null){  
                                rowList.add("");  
                                continue;  
                            }                             
                            rowList.add(getXValue(cell).trim());
                        }     
                    list.add(rowList);                                            
                    }  
                }  
            }  
            return list;  
        } catch (Throwable e) {
            e.printStackTrace();  
        } finally{  
            try {  
                input.close();  
            } catch (Throwable e) {
                e.printStackTrace();  
            }  
        }  
        return null;  
          
    }  

    /** 
     * read the Excel 2010 .xlsx 
     * @param file
     * @return 
     * @throws IOException  
     */  
    public static Map<String, String> readXlsxHeader(MultipartFile file , int startRow , int endRow){  
    	// IO流读取文件  
    	InputStream input = null;  
    	XSSFWorkbook wb = null;  
    	Map<String, String> map = new HashMap<String, String>();
    	try {  
    		input = file.getInputStream();  
    		// 创建文档  
    		wb = new XSSFWorkbook(input);                         
    		//读取sheet(页)  
    		for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){  
    			XSSFSheet xssfSheet = wb.getSheetAt(numSheet);  
    			if(xssfSheet == null){  
    				continue;  
    			}  
    			if(endRow != 0){
    				totalRows = endRow;                
    			}else{
    				totalRows = xssfSheet.getLastRowNum();                
    			}
    			//读取Row,从第三行开始
    			for(int rowNum = startRow;rowNum <= endRow;rowNum++){
    				XSSFRow xssfRow = xssfSheet.getRow(rowNum);  
    				if(xssfRow!=null){  
    					totalCells = xssfRow.getLastCellNum();  
//    					String lastTitle = "";
    					//读取列,从第一列开始  
    					for(int c=0;c<totalCells;c++){  
    						XSSFCell cell = xssfRow.getCell(c);  
    						if(map.get(Integer.toString(c))!=null){
    							if(cell!=null){  
    								String val = getXValue(cell).trim();
    								map.put(Integer.toString(c), map.get(Integer.toString(c))+"-"+val);
    							}    
    						}else{
    							if(cell==null){  
    								map.put(Integer.toString(c), "");
    								continue;  
    							}                             
    							map.put(Integer.toString(c), getXValue(cell).trim());
//    							lastTitle = getXValue(cell).trim();
    						}
    					}     
    				}  
    			}  
    		}  
    		return map;  
    	} catch (Throwable e) {
    		e.printStackTrace();  
    	} finally{  
    		try {  
    			input.close();  
    		} catch (Throwable e) {
    			e.printStackTrace();  
    		}  
    	}  
    	return null;  
    	
    }  
       
    /** 
     * 单元格格式 
     * @param xssfCell 
     * @return 
     */  
    public static String getXValue(XSSFCell xssfCell){  
         if (xssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {  
             return String.valueOf(xssfCell.getBooleanCellValue());  
         } else if (xssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {  
             String cellValue = "";  
             if(XSSFDateUtil.isCellDateFormatted(xssfCell)){  
                 Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue());  
                 cellValue = sdf.format(date);  
             }else{  
                 DecimalFormat df = new DecimalFormat("#.##");  
                 cellValue = df.format(xssfCell.getNumericCellValue());  
                 String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());  
                 if(strArr.equals("00")){  
                     cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));  
                 }    
             }  
             return cellValue;  
         } else {  
            return String.valueOf(xssfCell.getStringCellValue());  
         }  
    }   

    static class XSSFDateUtil extends DateUtil{  
	    protected static int absoluteDay(Calendar cal, boolean use1904windowing) {    
	        return DateUtil.absoluteDay(cal, use1904windowing);    
	    }   
	}
}

二:调用导入工具类,分别读取列头与行数据

@SuppressWarnings("unchecked")
	@RequestMapping(value = "batch/setting/importExl", method = RequestMethod.POST)
	@ResponseBody
	public String batchSettingImportExl(MultipartFile file) {
		logger.info("批量导入:开始!");
		String planMonth = com.yqjr.base.util.DateUtils.getYearMM();
		JSONObject object = new JSONObject();
		Map<String, String> title = new HashMap<String, String>();
		List<ArrayList<String>> planList = new ArrayList<ArrayList<String>>();
		try {
			title = ExcelRead.readXlsxHeader(file,1 , 2);//获取列头数据
			planList = ExcelRead.readExcel(file, 3, 0);//获取行数据
		} catch (Exception e) {
			logger.error("批量导入:异常:" , e);
			object.put("success", false);
			if (StringUtils.isNotBlank(e.getMessage())) {
				String msg = e.getMessage();
				if (msg.indexOf("valid") != -1) {
					object.put("message", msg.substring(6));
					object.put("valid", "valid");
					return object.toString();
				} else {
					object.put("message", msg);
					return object.toString();
				}
			}
		}
		object.put("success", true);
		return object.toString();
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值