Exel的读取操作

第一步:把需要的架包找到需要四个我
第二步:创建上传Exel表格jsp页面核心代码采用struts2
<form action="upload.action" method="post"
            enctype="multipart/form-data">
            <input type="file" name="uploadFile" /> <input name="submit"
                type="submit" value="导入exel" />
  </form>
第三步写出对应Action:
package com.pdsu.Action;

import java.io.File;
import java.util.List;

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

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.pdsu.service.exelService;
import com.pdsu.util.ExcelUtil;

public class ExelAction extends ActionSupport{

    /**
     *
     */
    private static final long serialVersionUID = 6892451861166250944L;
    private static final Logger logger = Logger.getLogger(ExelAction.class);
    private HttpServletRequest request = ServletActionContext.getRequest();
    private HttpServletResponse response = ServletActionContext.getResponse();
    private File uploadFile;
    private String uploadFileFileName;
    exelService service=new exelService();
    public File getUploadFile() {
        return uploadFile;
    }
    public void setUploadFile(File uploadFile) {
        this.uploadFile = uploadFile;
    }
    
    public String getUploadFileFileName() {
        return uploadFileFileName;
    }
    public void setUploadFileFileName(String uploadFileFileName) {
        this.uploadFileFileName = uploadFileFileName;
    }
    @Override
    public String execute() throws Exception {
        if (uploadFile == null) {
            request.setAttribute("message", "上传的资源为空");
            return SUCCESS;
        }
        System.out.println("uploadFileFileName"+uploadFileFileName);
        Workbook wb = ExcelUtil.loadExcel(uploadFile);
        if (wb == null) {
            request.setAttribute("message", "文件类型错误,这不是一个excel文件!");
            return SUCCESS;
        }
        
        boolean isLegalFile = service.checkIngotFile(wb);
        if (!isLegalFile) {
            request.setAttribute("message", "这不是一个合法的会员excel文件!");
            return SUCCESS;
        }

        String result = service.checkIngotData(wb);
        if (result != null && !result.isEmpty()) {
            request.setAttribute("message", result);
            return SUCCESS;
        }
        String message="";
        int zoneid = 0;
        List<Integer> failRows = service.importIngot(wb, zoneid);
        if (failRows.size() == 0) {
            message = "导入成功!";
        } else {
            String rows = "";
            for (Integer rowNum : failRows) {
                rows = rows + rowNum + ",";
            }
            rows.substring(0, rows.length() - 1);
            message = "导入失败!失败行号:" + rows;
        }
        
        logger.warn(message);
        request.setAttribute("message", message);
        return SUCCESS;
    }
}
第四步写出对应的service以及工具类ExcelUtil
service:
package com.pdsu.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.pdsu.bean.User;
import com.pdsu.util.ExcelUtil;
import com.pdsu.util.Validator;


public class exelService {
    private static final String RETRUN = "\\r\\n";

    private static final String[] ENAMES = new String[] { "id", "name","description"};
    private static final String[] CNAMES = new String[] { "会员ID", "会员名称", "会员描述" };
    public boolean checkIngotFile(Workbook wb) {
        Sheet sheet = wb.getSheetAt(0);

        Row enames = sheet.getRow(1);
        Row cnames = sheet.getRow(0);

        if (enames == null || cnames == null) {
            return false;
        }

        for (int i = 0; i < ENAMES.length; i++) {
            if (!ENAMES[i]
                    .equalsIgnoreCase(ExcelUtil.getStringOfRow(enames, i))) {
                return false;
            }
            if (!CNAMES[i]
                    .equalsIgnoreCase(ExcelUtil.getStringOfRow(cnames, i))) {
                return false;
            }
        }

        return true;
    }
    public String checkIngotData(Workbook wb) {
        StringBuilder message = new StringBuilder();
        Sheet sheet = wb.getSheetAt(0);
        int rowCount = sheet.getLastRowNum();//获取exel表格内数据的行数
        for (int i = 2; i < rowCount; i++) {
            Row row=sheet.getRow(i);
            try {
                int id = (int) ExcelUtil.getNumericOfRow(row, 0);
                if (id == 0) {
                    message.append(CNAMES[0] + "不合法!行号:" + (i + 1));
                    message.append(RETRUN);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(Validator.isNullOrEmpty(ExcelUtil.getStringOfRow(row, 1))){
                message.append(CNAMES[1] + "不能为空!行号:" + (i + 1));
                message.append(RETRUN);
            }
            if(Validator.isNullOrEmpty(ExcelUtil.getStringOfRow(row, 2))){
                message.append(CNAMES[2] + "不能为空!行号:" + (i + 1));
                message.append(RETRUN);
            }
            
        }
        return null;
    }
    public List<Integer> importIngot(Workbook wb, int zoneid) {
        List<Integer> failRows = new ArrayList<Integer>();
        List<User> userlist=new ArrayList<User>();
        User user=new User();
        Sheet sheet = wb.getSheetAt(0);
        int rowCount = sheet.getPhysicalNumberOfRows();
        for (int i = 2; i < rowCount; i++) {
            Row row = sheet.getRow(i);

            int id = (int) ExcelUtil.getNumericOfRow(row, 0);
            String name = ExcelUtil.getStringOfRow(row, 1);
            String description = ExcelUtil.getStringOfRow(row, 2);
            user.setId(id);
            user.setName(name);
            user.setDescription(description);
            System.out.println("id="+id+"name"+name+"description"+description);
            userlist.add(user);
        }
        
        return failRows;
    }

}
ExcelUtil:
package com.pdsu.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

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.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {

    public static Workbook loadExcel(File file) {
        InputStream is = null;
        Workbook wb = null;
            try {
                is = new FileInputStream(file);
                wb = new HSSFWorkbook(is);
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if (is != null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        }
            return wb;

    }

    public static String getStringOfRow(Row row, int columnIndex) {
        Cell cell = row.getCell(columnIndex, Row.CREATE_NULL_AS_BLANK);
        if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        return cell.getStringCellValue();
    }
        // 获取指定行的指定数字列的值
        public static double getNumericOfRow(Row row, int columnIndex) {
            Cell cell = row.getCell(columnIndex, Row.CREATE_NULL_AS_BLANK);

            return cell.getNumericCellValue();
        }
        
        // 获取指定行的指定数字列的值
        public static Date getDateOfRow(Row row, int columnIndex){
            Cell cell = row.getCell(columnIndex, Row.CREATE_NULL_AS_BLANK);
            
            return cell.getDateCellValue();
        }
}

最后在struts对Action进行配置

后语exel表格的格式


测试:上传成功


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值