excel 文件导入(jfinal框架下)

一、选择文件上传
html代码

    <form id="myFormId" action="user/initimport" method="post"enctype="multipart/form-data" target="frmright">
        <table class="tableStyle" formMode="transparent">
            <tr></tr>
            <tr>
                <td>
                <input type="file" id="filePath" name="filePath" class="validate[required]"/>
                </td>
            </tr>
            <tr>
                <td colspan="4">
                <input type="button" value="提交" id="btn" onclick='sub()'/>
                <input type="button" value="取消" onclick='top.Dialog.close()' /></td>
            </tr>
        </table>
    </form>

js代码

    function initComplete(){
        $('#myFormId').live('submit', function(){ 
        var valid = $('#myFormId').validationEngine({returnIsValid: true});
        if(valid){
        $("#btn").attr("disabled", "true");
            $(this).ajaxSubmit({
                success: function(responseText, statusText, xhr, $form){
                    top.Dialog.alert(responseText,
                            function() {
                                closeWin();
                            });
                }
            }); 
        }return false; 
        });
    }

        function closeWin() {
            //刷新数据
            top.frmright.refresh(true);
            //关闭窗口
            top.Dialog.close();
        }

        function sub() {
            $("#myFormId").submit();
        }

二、excel文件处理

    public void initimport(){
        boolean flag=Db.tx(new IAtom() {
            boolean save_flag =true;
            @Override
            public boolean run() throws SQLException {
                try {
                    UploadFile up = getFile("filePath");
                    List<String[]> list = ExcelKit.getExcelData(up.getFile());
                    for (String[] strings : list) {
                        if (strings[0] != null && !"".equals(strings[0])) {
                            String id = strings[0];
                            String username = strings[1];
                            String date = strings[2];
                            User user = new User();
                            if (!"".equals(username )) {
                                user.set("username",username);
                            }
                            if (!"".equals(date )) {
                                user.set("date",DateUtil.getSqlDate(date,"yyyy-MM-dd"));
                            }
                            save_flag = user.save();
                        }
                    }
                } catch (Exception e) {
                    save_flag = false;
                    e.printStackTrace();
                }
            return save_flag;
        }
    }

在excel单元格中,出现的数字可能会被自动转换格式。尤其是日期数据,比如2017-01-01,其结果就被转成2015。
excel的工具类方法ExcelKit.getData

    public List<String[]> getExcelData(File file){
        return getData(file).get(0);//选择sheet1
    }
    private static List<List<String[]>> getData(File file){
        HSSFWorkbook workbook;
        List<List<String[]>> data = new ArrayList<List<String[]>>();
        try {
            workbook = new HSSFWorkbook(new FileInputStream(file));
            HSSFSheet sheet=null;
            //循环sheet
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                sheet=workbook.getSheetAt(i);
                List<String[]> rows = new ArrayList<String[]>();
                int colsnum = 0;
                //循环每一行
                for (int j = 0; j <= sheet.getLastRowNum(); j++) {
                    HSSFRow row=sheet.getRow(j);
                    if(null != row){
                        //列数以excel第二行为准,第二行为标题,第一行为excel导入提示信息
                        colsnum = sheet.getRow(1).getPhysicalNumberOfCells();
                        String[] cols = new String[colsnum];
                        //循环每一个单元格,以一行为单位,组成一个数组
                        for (int k = 0; k < colsnum; k++) {
                            //判断单元格是否为null,若为null,则置空
                            if(null != row.getCell(k)) {
                                int type = row.getCell(k).getCellType();
                                //判断单元格数据是否为数字
                                if(type == HSSFCell.CELL_TYPE_NUMERIC){
                                    //判断该数字的计数方法是否为科学计数法,若是,则转化为普通计数法
                                    if(String.valueOf(row.getCell(k).getNumericCellValue()).matches(".*[E|e].*")) {
                                        DecimalFormat df = new DecimalFormat("#.#");
                                        //指定最长的小数点位为10
                                        df.setMaximumFractionDigits(10);
                                        cols[k] = df.format(row.getCell(k).getNumericCellValue());
                                    //判断该数字是否是日期,若是则转成字符串
                                    } else if(HSSFDateUtil.isCellDateFormatted(row.getCell(k))){
                                        Date d = row.getCell(k).getDateCellValue();
                                        DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
                                        cols[k] = formater.format(d);
                                    }else{
                                        cols[k] = (row.getCell(k)+"").trim();
                                    }
                                } else {
                                    cols[k] = (row.getCell(k)+"").trim();
                                }
                            } else {
                                cols[k] = "";
                            }
                        }
                        //以一行为单位,加入list
                        rows.add(cols);
                    }
                }
                //返回所有数据,第一个list表示sheet,第二个list表示sheet内所有行数据,第三个string[]表示单元格数据
                data.add(rows);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  data;
    }
/**
 * 获取sqldate,用以存入数据库
 * @param basicDate 存入日期
 * @param strFormat 日期格式
 * @return
 */
public static Timestamp getSqlDate(String basicDate, String strFormat){
    SimpleDateFormat df = new SimpleDateFormat(strFormat);
    Timestamp ts = null;
    try {
        ts = DateUtil.getSqlDate(df.parse(basicDate));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return ts;
}

···

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值