POI Excel 工具类 导入

工具类

package com.fty.util;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;




public class InputExcelUtil<T> {
	 /**
     * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出
     *
     * title         表格标题名
     * headersName  表格属性列名数组
     * headersId    表格属性列名对应的字段---你需要导出的字段名(为了更灵活控制你想要导出的字段)
     *  dtoList     需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象
     *  out         与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     */
    public   byte[] exportExcel(String title, List<String> headersName,List<String> headersId,
                            List<T> dtoList) {
        /*(一)表头--标题栏*/
        Map<Integer, String> headersNameMap = new HashMap<>();
        int key=0;
        for (int i = 0; i < headersName.size(); i++) {
            if (!headersName.get(i).equals(null)) {
                headersNameMap.put(key, headersName.get(i));
                key++;
            }
        }
        /*(二)字段*/
        Map<Integer, String> titleFieldMap = new HashMap<>();
        int value = 0;
        for (int i = 0; i < headersId.size(); i++) {
            if (!headersId.get(i).equals(null)) {
                titleFieldMap.put(value, headersId.get(i));
                value++;
            }
        }
        /* (三)声明一个工作薄:包括构建工作簿、表格、样式*/
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(title);
        sheet.setDefaultColumnWidth((short)15);
        // 生成一个样式
        HSSFCellStyle style = wb.createCellStyle();
        HSSFRow row = sheet.createRow(0);
       // style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFCell cell;
        Collection c = headersNameMap.values();//拿到表格所有标题的value的集合
        Iterator<String> it = c.iterator();//表格标题的迭代器
        /*(四)导出数据:包括导出标题栏以及内容栏*/
        //根据选择的字段生成表头
        short size = 0;
        while (it.hasNext()) {
            cell = row.createCell(size);
            cell.setCellValue(it.next().toString());
            cell.setCellStyle(style);
            size++;
        }
        //表格标题一行的字段的集合
        Collection zdC = titleFieldMap.values();
        Iterator<T> labIt = dtoList.iterator();//总记录的迭代器
        int zdRow =0;//列序号
        while (labIt.hasNext()) {//记录的迭代器,遍历总记录
            int zdCell = 0;
            zdRow++;
            row = sheet.createRow(zdRow);
            T l = (T) labIt.next();
            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
            Field[] fields = l.getClass().getDeclaredFields();//获得JavaBean全部属性
            for (short i = 0; i < fields.length; i++) {//遍历属性,比对
                Field field = fields[i];
                String fieldName = field.getName();//属性名
                Iterator<String> zdIt = zdC.iterator();//一条字段的集合的迭代器
                while (zdIt.hasNext()) {//遍历要导出的字段集合
                    if (zdIt.next().equals(fieldName)) {//比对JavaBean的属性名,一致就写入,不一致就丢弃
                        String getMethodName = "get"
                                + fieldName.substring(0, 1).toUpperCase()
                                + fieldName.substring(1);//拿到属性的get方法
                        Class tCls = l.getClass();//拿到JavaBean对象
                        try {
                            Method getMethod = tCls.getMethod(getMethodName,
                                    new Class[] {});//通过JavaBean对象拿到该属性的get方法,从而进行操控
                            Object val = getMethod.invoke(l, new Object[] {});//操控该对象属性的get方法,从而拿到属性值
                            String textVal = null;
                            if (val!= null) {
                                textVal = String.valueOf(val);//转化成String
                            }else{
                                textVal = null;
                            }
                            row.createCell((short) zdCell).setCellValue(textVal);//写进excel对象
                            zdCell++;
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return wb.getBytes();
    }
    /**
     * Excel读取 操作
     */
    public static List<List<String>> readExcel(InputStream is)
            throws IOException, InvalidFormatException {
        Workbook wb = null;
        try {  
              wb = WorkbookFactory.create(is);        
            } catch (FileNotFoundException e) {  
              e.printStackTrace();  
            } catch (IOException e) {  
              e.printStackTrace();  
            }  
 
        /** 得到第一个sheet */
        Sheet sheet = wb.getSheetAt(0);
        /** 得到Excel的行数 */
        int totalRows = sheet.getPhysicalNumberOfRows();
 
        /** 得到Excel的列数 */
        int totalCells = 0;
        if (totalRows >= 1 && sheet.getRow(0) != null) {
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
 
        List<List<String>> dataLst = new ArrayList<List<String>>();
        /** 循环Excel的行 */
        for (int r = 0; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null)
                continue;
            List<String> rowLst = new ArrayList<String>();
            /** 循环Excel的列 */
            for (int c = 0; c < totalCells; c++) {
                Cell cell = row.getCell(c);
                String cellValue = "";
                if (null != cell) {
                     /*HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
                     cellValue= hSSFDataFormatter.formatCellValue(cell);*/
 
                   // 以下是判断数据的类型
                	CellType type = cell.getCellTypeEnum();
 
                    switch (type) {
                    case NUMERIC: // 数字
                        cellValue = cell.getNumericCellValue() + "";
                        break;
                    case STRING: // 字符串
                        cellValue = cell.getStringCellValue();
                        break;
                    case BOOLEAN: // Boolean
                        cellValue = cell.getBooleanCellValue() + "";
                        break;
                    case FORMULA: // 公式
                        try {
                            cellValue = cell.getStringCellValue();
                        } catch (IllegalStateException e) {
                            cellValue = String.valueOf(cell.getNumericCellValue());
                        }
                        break;
                       /* cellValue = cell.getCellFormula() + "";
                        break;*/
                    case BLANK: // 空值
                        cellValue = "";
                        break;
                    case _NONE: // 故障
                        cellValue = "非法字符";
                        break;
                    default:
                        cellValue = "未知类型";
                        break;
                    }
                }
                rowLst.add(cellValue);
            }
            /** 保存第r行的第c列 */
            dataLst.add(rowLst);
        }
        return dataLst;
    }

}

controller类

import java.io.IOException;

import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import com.fty.entity.Merch;

import com.fty.service.MerchServiceImpl;

import com.fty.util.ExportExcelkit;
import com.fty.util.InputExcelUtil;
import com.fty.util.UtilId;


import org.springframework.util.CollectionUtils;






@RequestMapping(value="/inputs.action")
    @ResponseBody
    public void  inputs(@RequestParam(value="file")MultipartFile file,HttpServletResponse response,HttpServletRequest request)throws IOException, InvalidFormatException  {
    	
    	
    	
    	 //读取excel表格
        try {
            List<List<String>> lists = InputExcelUtil.readExcel(file.getInputStream());
            
            //判断集合是否为空
            if(!CollectionUtils.isEmpty(lists)){
            	for(int i = 1;i<lists.size();i++){
                    List<String> list = lists.get(i);
                    for(int j=0;j<list.size();j++) {
                    	
                    	Map<String, Object> map=new HashMap<String, Object>();
                		map.put("Name", list.get(1));
                		map.put("Factory", list.get(2));
                		map.put("Package", list.get(3));
                		map.put("Price", list.get(4));
                		map.put("Code", UtilId.generateId());
                		int ac=ssi.add(map);
                		System.out.println(ac);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
		}
    	
    }

前台JSP页面
From表单提交哦

head代码块
<form id="upload-form" method="POST" action="/import" enctype="multipart/form-data">
      <label for="file">导入商品数据:</label>
    <input type="file" name="file" id="excelfile" value="" />
    
    <input type="button"  id="upload" value="上传"/>
</form>
js代码块
$("#upload").click(function(){
		        var file = new FormData(document.getElementById("upload-form"));
		        $.ajax({
		            url:"${pageContext.request.contextPath}/Merch/inputs.action",
		            type:"post",
		            data:file,
		            contentType:false, //- 必须false才会自动加上正确的Content-Type
		            processData: false, //- 必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
		            success:function(){
		                
		                $('#drr').window('close');
		                $("#cx").click();
		                
		            },
		            error:function(){
		                alert("失败请重新选择");
		            }
		        });
		    });


mvc servlet 里一定要加一段上传文件的大小

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="utf-8" />  
        <!-- 指定所上传文件的总大小不能超过10485760000B。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
        <property name="maxUploadSize" value="10485760000" />  
        <property name="maxInMemorySize" value="40960" />  
    </bean>  

第一次写没什么经验不喜勿喷
可以留个邮箱我给你发源码 或者加我QQ1052678420也能发

发布了40 篇原创文章 · 获赞 53 · 访问量 7721

猜你喜欢

转载自blog.csdn.net/qq_44758351/article/details/104177169