java导入导出excel文件

java导入导出excel文件

我们项目中经常用到导入导出excel文件功能,现在汇总整理下导入导出核心工具类。

导入导出依赖

        <dependency>
			<groupId>org.apache.poigroupId>
			<artifactId>poiartifactId>
			<version>3.14version>
		dependency>
		<dependency>
			<groupId>org.apache.poigroupId>
			<artifactId>poi-ooxmlartifactId>
			<version>3.14version>
		dependency>

		<dependency>
			<groupId>commons-fileuploadgroupId>
			<artifactId>commons-fileuploadartifactId>
			<version>1.2.1version>
		dependency>

		<dependency>
			<groupId>commons-iogroupId>
			<artifactId>commons-ioartifactId>
			<version>2.2version>
		dependency>

导入导出核心代码

package com.yuhui.gzdc.server.common.util;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class ExcelUtil<T> {

	private Workbook workbook = null;
	private Sheet sheet = null;
	private String[] columnArray = null;
	private List<String[]> rowList = new ArrayList<String[]>();
	private String fileName = "";
	private String fileDeskDir = "";
	private final static String excel2003L =".xls";    //2003- 版本的excel
	private final static String excel2007U =".xlsx";   //2007+ 版本的excel
	private static Integer maxCount = 50000;
//	@Value("${poi.sheetMaxCount}")
	public void setMaxCount(Integer maxCount) {
		ExcelUtil.maxCount = maxCount;
	}

	/**
	 * 文件后缀名
	 */
	private String fileExt = "";

	public ExcelUtil() {
	}

	/**
	 * 
	 * @param fileDeskDir
	 *            保存图片相对路径
	 * @param filePath
	 *            Excel文档文件l
	 */
	public ExcelUtil(String fileDeskDir, String filePath) {
		this.fileDeskDir = fileDeskDir;
		File file = new File(filePath);
		fileName = file.getName();
		fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
		try {
			InputStream inputStream = new FileInputStream(file);
			// 根据后缀判断excel 2003 or 2007+
			if (fileExt.equals("xls")) {
				workbook = WorkbookFactory.create(inputStream);
			} else {
				workbook = new XSSFWorkbook(inputStream);
			}
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

     /**
     * 获取实体对象返回属性名称
     * @param obj 实体对象
     * @return
     * @throws Exception
     */
	public java.lang.reflect.Field[] findEntityAllTypeName(T obj)throws Exception{
		Class<? extends T> cls = (Class<? extends T>) obj.getClass();
		return cls.getDeclaredFields();
	}


    /**
     * 根据文件选择excel版本
     * @return
     * @throws Exception
     */
	public Workbook chooseWorkbook(MultipartFile file) throws Exception{
        Workbook workbook = null;
		//把MultipartFile转化为File
		CommonsMultipartFile cmf = (CommonsMultipartFile)file;
		DiskFileItem dfi = (DiskFileItem) cmf.getFileItem();
        File fo = dfi.getStoreLocation();

		String filename = file.getOriginalFilename();
		String fileType = (filename.substring(filename.lastIndexOf("."), filename.length())).toLowerCase();
		if(excel2003L.equals(fileType)){
            //2003-
			workbook = new HSSFWorkbook(FileUtils.openInputStream(fo));
		}else if(excel2007U.equals(fileType)){
            //2007+
			workbook = new XSSFWorkbook(FileUtils.openInputStream(fo));
		}else{
			throw new Exception("解析的文件格式有误!");
		}
		return workbook;
	}

    /**
     * 公共的导入excel方法
     * @param file 文件
     * @param obj 实体类
     * @return
     * @throws IOException
     */
    public List<T> importBaseExcel(MultipartFile file,T obj) throws IOException{

        Workbook workbook = null;
        List<T> list = new ArrayList<>();

        try {
            //读取文件内容
            workbook = this.chooseWorkbook(file);

            int sheets = workbook.getNumberOfSheets();
            for (int k = 0; k < sheets; k++) {
                //获取工作表
                Sheet sheet = workbook.getSheetAt(k);
                if(sheet==null){continue;}

                //获取sheet中第一行行号
                int firstRowNum = sheet.getFirstRowNum();
                //获取sheet中最后一行行号
                int lastRowNum = sheet.getLastRowNum();

                //获取该实体所有定义的属性 返回Field数组
                java.lang.reflect.Field[] entityName = this.findEntityAllTypeName(obj);

                String classname =  obj.getClass().getName();
                Class<?> clazz = Class.forName(classname);

                //循环插入数据
                for(int i=firstRowNum+1;i<=lastRowNum;i++){

                    Row row = sheet.getRow(i);

                    //可以根据该类名生成Java对象
                    T pojo = (T) clazz.newInstance();

                    //除自增编号外,实体字段匹配sheet列
                    for(int j = 0;j < entityName.length-1;j++){

                        //获取属性的名字,将属性的首字符大写,方便构造set方法
                        String name = "set"+entityName[j].getName().substring(0, 1).toUpperCase().concat(entityName[j].getName().substring(1))+"";
                        //获取属性的类型
                        String type = entityName[j].getGenericType().toString();

                        Method m = null;
                        //getMethod只能调用public声明的方法,而getDeclaredMethod基本可以调用任何类型声明的方法
                        m = obj.getClass().getDeclaredMethod(name,entityName[j].getType());

                        Cell pname = row.getCell(j);
                        //根据属性类型装入值
                        switch (type) {
                            case "char":
                            case "java.lang.Character":
                            case "class java.lang.String":
                                m.invoke(pojo,getValue(pname));
                                break;
                            case "int":
                            case "class java.lang.Integer":
                                m.invoke(pojo,Integer.valueOf(getValue(pname)));
                                break;
                            case "class java.util.Date":
                                m.invoke(pojo, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getValue(pname)));
                                break;
                            case "float":
                            case "double":
                            case "java.lang.Double":
                            case "java.lang.Float":
                            case "java.lang.Long":
                            case "java.lang.Short":
                            case "java.math.BigDecimal":
                                m.invoke(pojo,Double.valueOf(getValue(pname)));
                                break;
                            default:
                                break;
                        }
                    }
                    list.add(pojo);
                }
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workbook.close();
        }
        return null;
    }


	/**
	 * 获取所有文字数据,如果有图片,自动保存图片并封装图片路径到rowList集合
	 * 
	 * @return 文字数据(包括图片路径)的集合
	 */
	public List<String[]> getTextAndImg() {
		List<String[]> rowList = getText();
		// 如果有图片,自动保存图片并封装图片路径到rowList集合
		List<String> imgPaths = getAndSaveExcelImg();
		if (imgPaths != null && imgPaths.size() > 0) {
			for (int i = 0; i < rowList.size(); i++) {
				for (int j = 0; j < rowList.get(i).length; j++) {
					for (String imgPath : imgPaths) {
						// 获取图片的行索引
						int imgRowIndex = Integer.parseInt(imgPath.split("_")[1]);
						// 获取图片的列索引
						int imgColIndex = Integer
								.parseInt(imgPath.substring(imgPath.lastIndexOf("_") + 1, imgPath.lastIndexOf(".")));
						// 如果文字的行、列索引==图片的行、列索引
						if (i == imgRowIndex && j == imgColIndex) {
							rowList.get(i)[imgColIndex] = imgPath;
						}
					}
				}
			}
		}
		return rowList;
	}

	/**
	 * 获取excel中 图片,得到图片位置,并保存到D:/ExcelImg,以文档名为文件夹,
	 * 以图片位置索引命名,例如:Img0_1_0.png表示该图片位于第一个sheet的第2行第1列 支持03 07 多sheet
	 *
	 * @return 图片的相对路径集合
	 */
	public List<String> getAndSaveExcelImg() {
		if (workbook != null) {
			int sheetNumbers = workbook.getNumberOfSheets();
			List<Map<String, PictureData>> sheetList = new ArrayList<Map<String, PictureData>>();
			for (int i = 0; i < sheetNumbers; i++) {
				sheet = workbook.getSheetAt(i);
				// map等待存储excel图片
				Map<String, PictureData> sheetIndexPicMap;
				// 判断用07还是03的方法获取图片
				if (fileExt.equals("xls")) {
					sheetIndexPicMap = getSheetPictrues03(i, (HSSFSheet) sheet, (HSSFWorkbook) workbook);
				} else {
					sheetIndexPicMap = getSheetPictrues07(i, (XSSFSheet) sheet, (XSSFWorkbook) workbook);
				}
				// 将当前sheet图片map存入list
				if (sheetIndexPicMap != null && sheetIndexPicMap.size() > 0) {
					sheetList.add(sheetIndexPicMap);
				}
			}
			if (sheetList != null && sheetList.size() > 0) {
				return saveImgs(fileName, sheetList);
			}
		}
		return null;
	}

	/**
	 * 获取Excel2003图片
	 * 
	 * @param sheetNum
	 *            当前sheet编号
	 * @param sheet
	 *            当前sheet对象
	 * @param workbook
	 *            工作簿对象
	 * @return Map key:图片单元格索引(0_1_1)String,value:图片流PictureData
	 * @throws IOException
	 */
	private Map<String, PictureData> getSheetPictrues03(int sheetNum, HSSFSheet sheet, HSSFWorkbook workbook) {
		Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
		List<HSSFPictureData> pictures = workbook.getAllPictures();
		if (pictures.size() != 0) {
			for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
				HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
				if (shape instanceof HSSFPicture) {
					HSSFPicture pic = (HSSFPicture) shape;
					int pictureIndex = pic.getPictureIndex() - 1;
					HSSFPictureData picData = pictures.get(pictureIndex);
					String picIndex = String.valueOf(sheetNum) + "_" + String.valueOf(anchor.getRow1()) + "_"
							+ String.valueOf(anchor.getCol1());
					sheetIndexPicMap.put(picIndex, picData);
				}
			}
			return sheetIndexPicMap;
		} else {
			return null;
		}
	}

	/**
	 * 获取Excel2007图片
	 * 
	 * @param sheetNum
	 *            当前sheet编号
	 * @param sheet
	 *            当前sheet对象
	 * @param workbook
	 *            工作簿对象
	 * @return Map key:图片单元格索引(0_1_1)String,value:图片流PictureData
	 */
	private Map<String, PictureData> getSheetPictrues07(int sheetNum, XSSFSheet sheet, XSSFWorkbook workbook) {
		Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
		for (POIXMLDocumentPart dr : sheet.getRelations()) {
			if (dr instanceof XSSFDrawing) {
				XSSFDrawing drawing = (XSSFDrawing) dr;
				List<XSSFShape> shapes = drawing.getShapes();
				for (XSSFShape shape : shapes) {
					XSSFPicture pic = (XSSFPicture) shape;
					XSSFClientAnchor anchor = pic.getPreferredSize();
					CTMarker ctMarker = anchor.getFrom();
					String picIndex = String.valueOf(sheetNum) + "_" + ctMarker.getRow() + "_" + ctMarker.getCol();
					sheetIndexPicMap.put(picIndex, pic.getPictureData());
				}
			}
		}
		return sheetIndexPicMap;
	}

	/**
	 * 保存图片到硬盘,并返回图片相对路径集合
	 * 
	 * @param fileName
	 * @param sheetList
	 * @return
	 */
	private List<String> saveImgs(String fileName, List<Map<String, PictureData>> sheetList) {
		List<String> relativePaths = new ArrayList<String>();
		String dirName = fileName.substring(0, fileName.lastIndexOf("."));
		String fileDir = fileDeskDir + "/" + dirName;
		File file = new File(fileDir);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
		if (sheetList != null && sheetList.size() > 0) {
			for (Map<String, PictureData> map : sheetList) {
				Object key[] = map.keySet().toArray();
				for (int i = 0; i < map.size(); i++) {
					// 获取图片流
					PictureData pic = map.get(key[i]);
					// 获取图片索引
					String picName = key[i].toString();
					// 获取图片格式
					String ext = pic.suggestFileExtension();
					String picPath = fileDir + "/Img" + picName + "." + ext;
					byte[] data = pic.getData();
					try {
						FileOutputStream out = new FileOutputStream(picPath);
						System.out.println("已将图片保存到:" + picPath);
						out.write(data);
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					relativePaths.add(dirName + "/Img" + picName + "." + ext);
				}
			}
		}

		return relativePaths;
	}

	/**
	 * 根据后缀名判断是03还是07版,调用相应方法获取文档文字
	 * 
	 * @return List即:行集合<该行每一个单元格的值组成的数组>
	 */
	public List<String[]> getText() {
		if (workbook != null) {
			if (fileExt.equals("xlsx")) {
				return getSheetText07(0, (XSSFWorkbook) workbook);
			} else if (fileExt.equals("xls")) {
				return getSheetText03(0, (HSSFWorkbook) workbook);
			} else {
				System.out.println("该文件不是标准的Excel文件");
			}
		}
		return null;
	}

	/**
	 * 获取o3版文字内容
	 * 
	 * @param sheetIndex
	 * @param workbook
	 * @return
	 */
	public List<String[]> getSheetText03(int sheetIndex, HSSFWorkbook workbook) {
		/* 读EXCEL文字内容 */
		HSSFSheet hssfSheet = (HSSFSheet) workbook.getSheetAt(sheetIndex);
		int colCount = hssfSheet.getRow(0).getPhysicalNumberOfCells();
		for (int rowNum = 0; rowNum < hssfSheet.getPhysicalNumberOfRows(); rowNum++) {
			HSSFRow hssfRow = hssfSheet.getRow(rowNum);
			if (hssfRow != null) {
				columnArray = new String[colCount];
				for (int colNum = 0; colNum < colCount; colNum++) {
					columnArray[colNum] = getValue(hssfRow.getCell(colNum));
				}
			}else{
				break;
			}
			rowList.add(columnArray);
		}
		return rowList;
	}

	/**
	 * 获取o7+版文字内容
	 * 
	 * @param sheetIndex
	 * @param workbook
	 * @return
	 */
	private List<String[]> getSheetText07(int sheetIndex, XSSFWorkbook workbook) {
		/* 读EXCEL文字内容 */
		XSSFSheet xssfSheet = (XSSFSheet) workbook.getSheetAt(sheetIndex);
		int colCount = xssfSheet.getRow(0).getPhysicalNumberOfCells();
		for (int rowNum = 0; rowNum < xssfSheet.getPhysicalNumberOfRows(); rowNum++) {
			XSSFRow xssfRow = xssfSheet.getRow(rowNum);
			if (xssfRow != null) {
				columnArray = new String[colCount];
				for (int colNum = 0; colNum < colCount; colNum++) {
					columnArray[colNum] = getValue(xssfRow.getCell(colNum));
				}
			}else{
				break;
			}
			rowList.add(columnArray);
		}
		return rowList;
	}

	/**
	 * 获取单元格的值以字符串返回;03,07通用
	 * 
	 * @param cell
	 * @return
	 */
	private String getValue(Cell cell) {
		String value = null;
		if (cell != null) {
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				value = String.valueOf(cell.getBooleanCellValue());
				break;
			case XSSFCell.CELL_TYPE_NUMERIC:
				if(HSSFDateUtil.isCellDateFormatted(cell)){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					value= sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
				}else{
					value = new DecimalFormat("#").format(cell.getNumericCellValue());
				}
				break;
			case XSSFCell.CELL_TYPE_FORMULA:
				value = cell.getCellFormula();
				break;
			case XSSFCell.CELL_TYPE_ERROR:
				cell.setCellType(XSSFCell.CELL_TYPE_STRING);
				value = cell.getStringCellValue();
				break;
			default:
				value = String.valueOf(cell.getStringCellValue());
				break;
			}
		}
		return value;
	}

	/**
	 * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
	 * 
	 * @param title
	 *            表格标题名
	 * @param headers
	 *            表格属性列名数组
	 * @param dataset
	 *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
	 *            javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
	 * @param out
	 *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
	 * @param pattern
	 *            如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
	 */
	@SuppressWarnings("unchecked")
	public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
		Integer totalCount = dataset.size();
		Integer sheetCount;
		if (totalCount == 0) {
			sheetCount = 1;
		} else {
			sheetCount = (totalCount + ExcelUtil.maxCount - 1) / ExcelUtil.maxCount;
		}
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 12);
//		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);
		// 生成并设置另一个样式
		HSSFCellStyle style2 = workbook.createCellStyle();
		// 生成另一个字体
		HSSFFont font2 = workbook.createFont();
		font2.setFontHeightInPoints((short) 11);
		font2.setColor(HSSFColor.BLACK.index);
		// 把字体应用到当前的样式
		style2.setFont(font2);
		HSSFFont font3 = workbook.createFont();
		// 遍历集合数据,产生数据行
		Iterator<T> it = dataset.iterator();
		for (Integer i = 0; i < sheetCount; i++) {
			// 生成一个表格
			HSSFSheet sheet = workbook.createSheet(title + (i + 1));
			// 设置表格默认列宽度为15个字节
			sheet.setDefaultColumnWidth((short) 20);
			// 声明一个画图的顶级管理器
			HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
			// 产生表格标题行
			HSSFRow row = sheet.createRow(0);
			for (int j = 0; j < headers.length; j++) {
				HSSFCell cell = row.createCell(j);
				cell.setCellStyle(style);
				HSSFRichTextString text = new HSSFRichTextString(headers[j]);
				cell.setCellValue(text);
			}
			int index = 0;
			while (it.hasNext()) {
				index++;
				if (index == maxCount + 1) {
					break;
				}
				row = sheet.createRow(index);
				T t = (T) it.next();
				// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
				Field[] fields = t.getClass().getDeclaredFields();
				for (int k = 0; k < fields.length; k++) {
					HSSFCell cell = row.createCell(k);
					cell.setCellStyle(style2);
					Field field = fields[k];
					String fieldName = field.getName();
					String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
					try {
						Class tCls = t.getClass();
						Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
						Object value = getMethod.invoke(t, new Object[] {});
						// 判断值的类型后进行强制类型转换
						String textValue = null;
						if (value instanceof Boolean) {
							boolean bValue = (Boolean) value;
							textValue = "男";
							if (!bValue) {
								textValue = "女";
							}
						} else if (value instanceof Date) {
							Date date = (Date) value;
							SimpleDateFormat sdf = new SimpleDateFormat(pattern);
							textValue = sdf.format(date);
						} else if (value instanceof byte[]) {
							// 有图片时,设置行高为60px;
							row.setHeightInPoints(60);
							// 设置图片所在列宽度为80px,注意这里单位的一个换算
							sheet.setColumnWidth(i, (short) (35.7 * 80));
							// sheet.autoSizeColumn(i);
							byte[] bsValue = (byte[]) value;
							HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6,
									index);
							anchor.setAnchorType(ClientAnchor.AnchorType.byId(2));
							patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
						} else {
							// 其它数据类型都当作字符串简单处理
							textValue = value == null ? "" : value.toString();
						}
						// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
						if (textValue != null) {
							Pattern p = Pattern.compile("^//d+(//.//d+)?$");
							Matcher matcher = p.matcher(textValue);
							if (matcher.matches()) {
								// 是数字当作double处理
								cell.setCellValue(Double.parseDouble(textValue));
							} else {
								HSSFRichTextString richString = new HSSFRichTextString(textValue);
								richString.applyFont(font3);
								cell.setCellValue(richString);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
		    }
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void exportExcel(String title, String[] headers, List<Map<String, Object>> dataset,ServletOutputStream out, String pattern,List<String> newEngHeadersList) {
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);
		// 设置表格默认列宽度为15个字节
		sheet.setDefaultColumnWidth((short) 20);
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置样式
//		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 12);
//		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);
		// 生成并设置另一个样式
		HSSFCellStyle style2 = workbook.createCellStyle();
//		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//		style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		// 生成另一个字体
		HSSFFont font2 = workbook.createFont();
		font2.setFontHeightInPoints((short) 11);
		font2.setColor(HSSFColor.BLACK.index);
		// 把字体应用到当前的样式
		style2.setFont(font2);

		// 声明一个画图的顶级管理器
		HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

		// 产生表格标题行
		HSSFRow row = sheet.createRow(0);
		for (short i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellStyle(style);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}
		HSSFFont font3 = workbook.createFont();

		// 遍历集合数据,产生数据行
		Iterator<Map<String, Object>> it = dataset.iterator();
		int index = 0;
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			Map<String, Object> map = it.next();
			for(int i=0;i<newEngHeadersList.size();i++){
				HSSFCell cell = row.createCell(i);
				cell.setCellStyle(style2);
				String textValue = (String) map.get(newEngHeadersList.get(i));
				textValue = textValue== null ? "" : textValue.toString();
				// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
				if (textValue != null) {
					Pattern p = Pattern.compile("^//d+(//.//d+)?$");
					Matcher matcher = p.matcher(textValue);
					if (matcher.matches()) {
						// 是数字当作double处理
						cell.setCellValue(Double.parseDouble(textValue));
					} else {
						HSSFRichTextString richString = new HSSFRichTextString(textValue);
						richString.applyFont(font3);
						cell.setCellValue(richString);
					}
				}
			}
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

使用说明:
1.导出功能:调用exportExcel()方法
示例如下:

            String fileName = java.net.URLEncoder.encode("投诉建议列表", "UTF-8");
            String fn = DateUtil.getNowTimeStampStr() + fileName;
            String headers[] = { "投诉建议单号", "类型","来源","状态",  "联系人", "联系人电话", "投诉建议内容", "投诉时间", "用户名称", "用户电话"};
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=\"" + fn + ".xls\"");
            response.setContentType("application/octet-stream;charset=utf-8");
            ServletOutputStream outputStream = response.getOutputStream();
            ExcelUtil<TbIntimateComplainDto> excelUtil = new ExcelUtil<>();

            excelUtil.exportExcel("投诉建议列表", headers, complainDtoList, outputStream, "");
            outputStream.flush();
            outputStream.close();
            System.out.println("导出投诉建议单信息成功!");

2.导入功能:调用importBaseExcel()方法
调用示例:

public String importMachineRoom(@RequestParam("file") MultipartFile file) {
        RsRoom rsRoom = new RsRoom();
        try {
        	// 调用方法
            List<RsRoom> rsRooms = excelUtil.importBaseExcel(file, rsRoom);
            rsRooms.forEach(rsRoom1 -> machineRoomService.insertMachineRoomSelective(rsRoom1));
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return formatResponseParams("导入信息异常", null);
        }
        return formatResponseParams(EXEC_OK, null);
    }

springboot架构,参数使用@RequestParam(“file”) MultipartFile file,同时需要在启动类Application中添加Been:MultipartResolver类,并阻止该类的自动配置
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})

	@Bean(name = "multipartResolver")
	public MultipartResolver multipartResolver(){
		CommonsMultipartResolver resolver = new CommonsMultipartResolver();
		resolver.setDefaultEncoding("UTF-8");
		//resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常
		resolver.setResolveLazily(true);
		return resolver;
	}

如果不配置,在调用CommonsMultipartFile cmf = (CommonsMultipartFile)file会报异常。

你可能感兴趣的:(java,导入导出excel)