jeesite4 导入导出

博客介绍了前端后端代码中的文件导入导出功能。导出以模板为例,生成指定文件后以流输出,处理临时文件删除问题;导入用工具类解析文件成列表,遍历处理数据存入数据库,解析时根据文件格式创建不同对象获取工作表数据。

页面做的比较粗糙,将就用下
在这里插入图片描述
前端代码:

<div style="position: absolute;right: 396px;top: 12px;">
	<a href="${ctx}/tdata/tdata/exportTemplate" onclick="return confirm('确定下载?');">下载模板</a>
</div>
<div style="position: absolute;right: 40px;top: 0px;">
	<form action="${ctx}/tdata/tdata/importFile" method="post" enctype="multipart/form-data">
		<div style="position: absolute;right: 66px;top: 10px;">
			<input id="file" type="file" name="file" accept=".xls,.xlsx" />
		</div>
		<div style="position: absolute;right: 108px;top: 7px;">
			<input id="submit" type="submit" value="导入" style="height: 30px;width: 60px;border-bottom-left-radius: 5px;
    		border-bottom-right-radius: 5px;border-top-left-radius: 5px;border-top-right-radius: 5px;background-color: lavender;" />
		</div>
	</form>
</div>
// 加载成功后执行事件
ajaxSuccess: function(data){
	var btn = document.getElementById("submit");
	btn.onclick=function(){
		var file = document.getElementById("file").value;
		if (file == "") {
			layer.open({
				content: '请先选择导入文件!',
				icon: 7,
				offset: 'rt',
				time:1000
			});
			return false;
		}
	}
}

后端代码:
导出工具类:

package com.jeesite.modules.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExportExcelUtil<T> {
	// 2007 版本以上 最大支持1048576行
	public  final static String  EXCEl_FILE_2007 = "2007";
	// 2003 版本 最大支持65536 行
	public  final static String  EXCEL_FILE_2003 = "2003";
	
	/**
	 * <p>
	 * 导出无头部标题行Excel <br>
	 * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
	 * </p>
	 * 
	 * @param title 表格标题
	 * @param dataset 数据集合
	 * @param out 输出流
	 * @param version 2003 或者 2007,不传时默认生成2003版本
	 */
	public void exportExcel(String title, Collection<T> dataset, OutputStream out, String version) {
		if(StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())){
			exportExcel2003(title, null, dataset, out, "yyyy-MM-dd HH:mm:ss");
		}else{
			exportExcel2007(title, null, dataset, out, "yyyy-MM-dd HH:mm:ss");
		}
	}
 
	/**
	 * <p>
	 * 导出带有头部标题行的Excel <br>
	 * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
	 * </p>
	 * 
	 * @param title 表格标题
	 * @param headers 头部标题集合
	 * @param dataset 数据集合
	 * @param out 输出流
	 * @param version 2003 或者 2007,不传时默认生成2003版本
	 */
	public void exportExcel(String title,String[] headers, Collection<T> dataset, OutputStream out,String version) {
		if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){
			exportExcel2003(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss");
		}else{
			exportExcel2007(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss");
		}
	}
 
	/**
	 * <p>
	 * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
	 * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
	 * </p>
	 * 
	 * @param title
	 *            表格标题名
	 * @param headers
	 *            表格头部标题集合
	 * @param dataset
	 *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
	 *            JavaBean属性的数据类型有基本数据类型及String,Date
	 * @param out
	 *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
	 * @param pattern
	 *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void exportExcel2007(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
		// 声明一个工作薄
		@SuppressWarnings("resource")
		XSSFWorkbook workbook = new XSSFWorkbook();
		// 生成一个表格
		XSSFSheet sheet = workbook.createSheet(title);
		// 设置表格默认列宽度为15个字节
		sheet.setDefaultColumnWidth(20);
		// 生成一个样式
		XSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
		style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
		style.setBorderRight(XSSFCellStyle.BORDER_THIN);
		style.setBorderTop(XSSFCellStyle.BORDER_THIN);
		style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		XSSFFont font = workbook.createFont();
		font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
		font.setFontName("宋体"); 
		font.setColor(new XSSFColor(java.awt.Color.BLACK));
		font.setFontHeightInPoints((short) 11);
		// 把字体应用到当前的样式
		style.setFont(font);
		// 生成并设置另一个样式
		XSSFCellStyle style2 = workbook.createCellStyle();
		style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
		style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
		style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
		style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
		style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
		style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
		style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
		style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
		// 生成另一个字体
		XSSFFont font2 = workbook.createFont();
		font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
		// 把字体应用到当前的样式
		style2.setFont(font2);
 
		// 产生表格标题行
		XSSFRow row = sheet.createRow(0);
		XSSFCell cellHeader;
		for (int i = 0; i < headers.length; i++) {
			cellHeader = row.createCell(i);
			cellHeader.setCellStyle(style);
			cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
		}
 
		// 遍历集合数据,产生数据行
		Iterator<T> it = dataset.iterator();
		int index = 0;
		T t;
		Field[] fields;
		Field field;
		XSSFRichTextString richString;
		Pattern p = Pattern.compile("^//d+(//.//d+)?$");
		Matcher matcher;
		String fieldName;
		String getMethodName;
		XSSFCell cell;
		Class tCls;
		Method getMethod;
		Object value;
		String textValue;
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			t = (T) it.next();
			// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
			fields = t.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				cell = row.createCell(i);
				cell.setCellStyle(style2);
				field = fields[i];
				fieldName = field.getName();
				getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
						+ fieldName.substring(1);
				try {
					tCls = t.getClass();
					getMethod = tCls.getMethod(getMethodName, new Class[] {});
					value = getMethod.invoke(t, new Object[] {});
					// 判断值的类型后进行强制类型转换
					textValue = null;
					if (value instanceof Integer) {
						cell.setCellValue((Integer) value);
					} else if (value instanceof Float) {
						textValue = String.valueOf((Float) value);
						cell.setCellValue(textValue);
					} else if (value instanceof Double) {
						textValue = String.valueOf((Double) value);
						cell.setCellValue(textValue);
					} else if (value instanceof Long) {
						cell.setCellValue((Long) value);
					}
					if (value instanceof Boolean) {
						textValue = "是";
						if (!(Boolean) value) {
							textValue = "否";
						}
					} else if (value instanceof Date) {
						textValue = sdf.format((Date) value);
					} else {
						// 其它数据类型都当作字符串简单处理
						if (value != null) {
							textValue = value.toString();
						}
					}
					if (textValue != null) {
						matcher = p.matcher(textValue);
						if (matcher.matches()) {
							// 是数字当作double处理
							cell.setCellValue(Double.parseDouble(textValue));
						} else {
							richString = new XSSFRichTextString(textValue);
							cell.setCellValue(richString);
						}
					}
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} finally {
					// 清理资源
				}
			}
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * <p>
	 * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
	 * 此方法生成2003版本的excel,文件名后缀:xls <br>
	 * </p>
	 * 
	 * @param title
	 *            表格标题名
	 * @param headers
	 *            表格头部标题集合
	 * @param dataset
	 *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
	 *            JavaBean属性的数据类型有基本数据类型及String,Date
	 * @param out
	 *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
	 * @param pattern
	 *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void exportExcel2003(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
		// 声明一个工作薄
		@SuppressWarnings("resource")
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);
		// 设置表格默认列宽度为15个字节
		sheet.setDefaultColumnWidth(20);
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		style.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		font.setFontName("宋体"); 
		font.setColor(HSSFColor.WHITE.index);
		font.setFontHeightInPoints((short) 11);
		// 把字体应用到当前的样式
		style.setFont(font);
		// 生成并设置另一个样式
		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setFillForegroundColor(HSSFColor.WHITE.index);
		style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		// 生成另一个字体
		HSSFFont font2 = workbook.createFont();
		font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		// 把字体应用到当前的样式
		style2.setFont(font2);
 
		// 产生表格标题行
		HSSFRow row = sheet.createRow(0);
		HSSFCell cellHeader;
		for (int i = 0; i < headers.length; i++) {
			cellHeader = row.createCell(i);
			cellHeader.setCellStyle(style);
			cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
		}
 
		// 遍历集合数据,产生数据行
		Iterator<T> it = dataset.iterator();
		int index = 0;
		T t;
		Field[] fields;
		Field field;
		HSSFRichTextString richString;
		Pattern p = Pattern.compile("^//d+(//.//d+)?$");
		Matcher matcher;
		String fieldName;
		String getMethodName;
		HSSFCell cell;
		Class tCls;
		Method getMethod;
		Object value;
		String textValue;
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			t = (T) it.next();
			// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
			fields = t.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				cell = row.createCell(i);
				cell.setCellStyle(style2);
				field = fields[i];
				fieldName = field.getName();
				getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
						+ fieldName.substring(1);
				try {
					tCls = t.getClass();
					getMethod = tCls.getMethod(getMethodName, new Class[] {});
					value = getMethod.invoke(t, new Object[] {});
					// 判断值的类型后进行强制类型转换
					textValue = null;
					if (value instanceof Integer) {
						cell.setCellValue((Integer) value);
					} else if (value instanceof Float) {
						textValue = String.valueOf((Float) value);
						cell.setCellValue(textValue);
					} else if (value instanceof Double) {
						textValue = String.valueOf((Double) value);
						cell.setCellValue(textValue);
					} else if (value instanceof Long) {
						cell.setCellValue((Long) value);
					}
					if (value instanceof Boolean) {
						textValue = "是";
						if (!(Boolean) value) {
							textValue = "否";
						}
					} else if (value instanceof Date) {
						textValue = sdf.format((Date) value);
					} else {
						// 其它数据类型都当作字符串简单处理
						if (value != null) {
							textValue = value.toString();
						}
					}
					if (textValue != null) {
						matcher = p.matcher(textValue);
						if (matcher.matches()) {
							// 是数字当作double处理
							cell.setCellValue(Double.parseDouble(textValue));
						} else {
							richString = new HSSFRichTextString(textValue);
							cell.setCellValue(richString);
						}
					}
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} finally {
					// 清理资源
				}
			}
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

导入工具类:

package com.jeesite.modules.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.ss.usermodel.WorkbookFactory;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

public class ImportExcelUtil {
	
	// 总行数
    private int totalRows = 0;
    // 总条数
    private int totalCells = 0;
    // 错误信息接收器
    private String errorMsg;
 
    // 构造方法
    public ImportExcelUtil() {
    }
 
    // 获取总行数
    public int getTotalRows() {
        return totalRows;
    }
 
    // 获取总列数
    public int getTotalCells() {
        return totalCells;
    }
 
    // 获取错误信息
    public String getErrorInfo() {
        return errorMsg;
    }
 
    /**
     * 读EXCEL文件,获取信息集合
     * 
     * @param fielName
     * @return
     */
    public List<Map<String, Object>> getExcelInfo(MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();// 获取文件名
 //       List<Map<String, Object>> userList = new LinkedList<Map<String, Object>>();
        try {
            if (!validateExcel(fileName)) {// 验证文件名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            return createExcel(mFile.getInputStream(), isExcel2003);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 根据excel里面的内容读取客户信息
     * 
     * @param is      输入流
     * @param isExcel2003   excel是2003还是2007版本
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> createExcel(InputStream is, boolean isExcel2003) {
        try {
           Workbook wb = null;
            if (isExcel2003) {// 当excel是2003时,创建excel2003
                wb = new HSSFWorkbook(is);
            } else {// 当excel是2007时,创建excel2007
            	try {
//                wb = new XSSFWorkbook(is);	//	这种方式创建对象会报错 Package should contain a content type part [M1.13]
					wb = WorkbookFactory.create(is);
				} catch (Exception e) {
					e.printStackTrace();
				}
            }
            return readExcelValue(wb);// 读取Excel里面客户的信息
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 读取Excel里面客户的信息
     * 
     * @param wb
     * @return
     */
    private List<Map<String, Object>> readExcelValue(Workbook wb) {
        // 得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数
        this.totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列数(前提是有行数)
        if (totalRows > 1 && sheet.getRow(0) != null) {
            this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
        // 循环Excel行数
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            // 循环Excel的列
            Map<String, Object> map = new HashMap<String, Object>();
            for (int c = 0; c < this.totalCells; c++) {
                Cell cell = row.getCell(c);
                if (null != cell) {
                    if (c == 0) {
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String name = String.valueOf(cell.getNumericCellValue());
                            map.put("tdid", name.substring(0, name.length() - 2 > 0 ? name.length() - 2 : 1));// tdid
                        } else {
                            map.put("tdid", cell.getStringCellValue());// tdid
                        }
                    } else if (c == 1) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String sex = String.valueOf(cell.getNumericCellValue());
                            map.put("fid",sex.substring(0, sex.length() - 2 > 0 ? sex.length() - 2 : 1));// fid
                        } else {
                            map.put("fid",cell.getStringCellValue());// fid
                        }
                    } else if (c == 2) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String age = String.valueOf(cell.getNumericCellValue());
                            map.put("tdzl", age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));// 土地坐落
                        } else {
                            map.put("tdzl", cell.getStringCellValue());// 土地坐落
                        }
                    } else if (c == 3) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String age = String.valueOf(cell.getNumericCellValue());
                            map.put("ywlx", age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));// 业务类型
                        } else {
                            map.put("ywlx", cell.getStringCellValue());// 业务类型
                        }
                    } else if (c == 4) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String age = String.valueOf(cell.getNumericCellValue());
                            map.put("area", age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));// 用地面积
                        } else {
                            map.put("area", cell.getStringCellValue());// 用地面积
                        }
                    } else if (c == 5) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String age = String.valueOf(cell.getNumericCellValue());
                            map.put("area2", age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));// 面积2
                        } else {
                            map.put("area2", cell.getStringCellValue());// 面积2
                        }
                    } else if (c == 6) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String age = String.valueOf(cell.getNumericCellValue());
                            map.put("projectname", age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));// 项目名称
                        } else {
                            map.put("projectname", cell.getStringCellValue());// 项目名称
                        }
                    } else if (c == 7) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String age = String.valueOf(cell.getNumericCellValue());
                            map.put("no", age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));// 编号
                        } else {
                            map.put("no", cell.getStringCellValue());// 编号
                        }
                    } else if (c == 8) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String age = String.valueOf(cell.getNumericCellValue());
                            map.put("x", age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));// x坐标
                        } else {
                            map.put("x", cell.getStringCellValue());// x坐标
                        }
                    } else if (c == 9) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String age = String.valueOf(cell.getNumericCellValue());
                            map.put("y", age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));// y坐标
                        } else {
                            map.put("y", cell.getStringCellValue());// y坐标
                        }
                    }
                }
            }
        	// 添加到list
            userList.add(map);
         }
	        return userList;
     }
	 /**
	  * 验证EXCEL文件
	  * @param filePath
	  * @return
	  */
	public boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }
	 
    // @描述:是否是2003的excel,返回true是2003
    public static boolean isExcel2003(String filePath) {
	    return filePath.matches("^.+\\.(?i)(xls)$");
    }
	  
    // @描述:是否是2007的excel,返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}

先介绍导出,以导出模板为例:先以工具类生成指定文件,也就是代码中的path,其中templatePath是随便给的一个绝对路径前缀,然后以流的形式将文件输出,最后关闭流并删除临时文件,之前一直删除不了临时文件,百度搜索了下,相关原因有流未关闭或是被别的进程使用,后经测试确认是被别的进程使用导致暂时无法删除,因此采用了无脑循环删除法进行强行删除,当然,采用注释掉的那段也行,先调用gc回收,再进行删除处理

/**
 * 导出模板
 * @param tdata
 * @param request
 * @param response
 * @return
 */
@RequiresPermissions("tdata:tdata:view")
@RequestMapping(value = "exportTemplate")
@ResponseBody
public String exportTemplate(Tdata tdata, HttpServletResponse response) {
	ExportExcelUtil<Tdata> util = new ExportExcelUtil<>();
	List<Tdata> list = new ArrayList<>();
	String columnNames[] = {"id", "ORIG_FID", "土地座落", "业务类型", "用地面积", "面积2", "项目名称", "图号", "x", "y"};
	File file = null;
	FileInputStream fis = null;
	OutputStream os = null;
	try {
		String path = templatePath+"template"+new SimpleDateFormat("yyyyMMdd").format(new Date())+".xlsx";
		util.exportExcel("模板导出", columnNames, list, new FileOutputStream(path), ExportExcelUtil.EXCEL_FILE_2003);
		file = new File(path);
		if (file.exists()) {
			String fileName = "template"+new SimpleDateFormat("yyyyMMdd").format(new Date())+".xlsx";
			fis = new FileInputStream(path);		// 读取要下载的文件 保存到文件输入流
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));	// 设置请求头
			os = response.getOutputStream();
			byte b[] = new byte[1024];
			int len = 0;
			while ((len = fis.read(b)) >0) {
				os.write(b, 0, len);
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		return renderResult(Global.FALSE, text("导出模板下载失败!失败信息:"+e.getMessage()));
	} finally {
		try {	// 关闭流
			if (fis !=null)
				fis.close();
			if (os !=null)
				os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
//	if (file.exists() && file.isFile()) {	// 删除临时文件
//		System.gc();
//		file.delete();
	}
	if (file.exists() && file.isFile()) {	// 强行删除临时文件
		boolean flag = file.delete();
		while (!flag) {
			flag = file.delete();
		}
	}
	return renderResult(Global.TRUE, text("导出模板下载成功!"));
}

然后是导入:导入功能主要是用工具类将文件解析成一个list集合,然后遍历list进行业务处理,比如遍历将数据存到数据库,工具类解析过程先是通过导入的文件判断文件格式是xls还是xlsx,通过格式的不同创建不同的对象,xls对应HSSFWorkbook,xlsx则以WorkbookFactory的create方法创建,然后通过getSheetAt(0)获取到第一个sheet工作表数据,再通过遍历将每行数据存入map,最后将所有map存入list

/**
 * 导入数据
 * @param tdata
 * @param file
 * @return
 */
@RequiresPermissions("tdata:tdata:edit")
@RequestMapping(value = "importFile")
@ResponseBody
public String importFile(Tdata tdata, MultipartFile file) {
	try {
		ImportExcelUtil util = new ImportExcelUtil();
		List<Map<String, Object>> list = util.getExcelInfo(file);
		if (list ==null) {
			return renderResult(Global.FALSE, text("导入数据失败!没有数据!"));
		}
		for (Map<String, Object> map : list) {	 
			// 逻辑处理
			
		}
	} catch (Exception e) {
		return renderResult(Global.FALSE, text("导入数据失败!失败信息:"+e.getMessage()));
	}
	return renderResult(Global.TRUE, text("导入数据成功!"));
}

导出效果图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值