javaweb Excel数据导入数据库

有需求把excel导入到数据库,很长时间没有写过文件IO方面的代码,第一时间没有选择用什么插件,第一时间就是找资料,

在这感谢http://blog.csdn.net/tmaskboy/article/details/51755305   文章java代码只是进行了部分改造

不多说直接上过程


读取文件流,页面需设置表单的MIME编码enctype="multipart/form-data",表单内容

		<form action="xxx" id="importExcelForm" method="post" enctype="multipart/form-data">
			<input type="file" name="excelFile" id="file" />
			<input type="button"  id="importExcel" class="uum_inputbutton" value="导入"> 
		</form>
如果需要使用异步上传,提交表单可以使用jquery.from.js

	$("#importExcelForm").ajaxSubmit({
            //定义返回JSON数据,还包括xml和script格式
            dataType:'json',
            beforeSend: function() {
                //表单提交前做表单验证
            }, 
            success: function(data) {
                //提交成功后调用
                alert(data);
                showProdList();
            },
            error:function(data){
            	alert(data);
            }
        });
java后端使用springmvc自动注入file对象,获取文件输入流,读取文件
@RequestMapping(value=Url.IMPORT_EXCEL_REWARD)
	public @ResponseBody String importExcelReward(HttpServletRequest req,HttpServletResponse resp,@RequestParam MultipartFile excelFile){
        String message = "";
        try {
        	List<Map<String, Object>> lists = ReadExcel.read2007Excel(excelFile.getInputStream());
            message = rewardService.importExcelReward(lists);
        } catch (Exception e) {
            e.printStackTrace();
            message = "导入失败!失败原因如下:<br>"+e.getMessage();
            return message;
        }
        return message;
	}
通过输入流读取文件

public static String[] paramArray = {"参数名称"....};
	
    /**
     * 读取Office 2007 excel
     * */
    public static List<Map<String, Object>> read2007Excel(InputStream fileInputStream)
            throws IOException {
        List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
        // 构造 XSSFWorkbook 对象,strPath 传入文件路径
        XSSFWorkbook xwb = new XSSFWorkbook(fileInputStream);
        // 读取第一章表格内容
        XSSFSheet sheet = xwb.getSheetAt(0);
        Object value = null;
        XSSFRow row = null;
        XSSFCell cell = null;
        int counter = 1;
        DecimalFormat df = new DecimalFormat("0");// 格式化 number String
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
        DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字
        for (int i = sheet.getFirstRowNum(); counter < sheet.getPhysicalNumberOfRows(); i++) {
            row = sheet.getRow(i);
            if (row == null||i==0) {		//表头不取
                continue;
            } else {
                counter++;
            }
            Map<String, Object> linked = new HashMap<String, Object>();
            for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
                cell = row.getCell(j);
                if (cell == null) {
                	value=null;
                }else{
	                switch (cell.getCellType()) {
		                case XSSFCell.CELL_TYPE_STRING:
		                    value = cell.getStringCellValue();
		                    break;
		                case XSSFCell.CELL_TYPE_NUMERIC:
		                    if ("@".equals(cell.getCellStyle().getDataFormatString())) {
		                        value = df.format(cell.getNumericCellValue());
		                    } else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
		                        value = nf.format(cell.getNumericCellValue());
		                    } else {
		                        value = sdf.format(HSSFDateUtil.getJavaDate(cell
		                                .getNumericCellValue()));
		                    }
		                    break;
		                case XSSFCell.CELL_TYPE_BOOLEAN:
		                    value = cell.getBooleanCellValue();
		                    break;
		                case XSSFCell.CELL_TYPE_BLANK:
		                    value = "";
		                    break;
		                default:
		                    value = cell.toString();
		                }
	                }
	            linked.put(paramArray[j],value);
            }
            list.add(linked);
        }
        return list;
    }

因为偷懒,我直接自己定义了一个String数据,put进map对象,想优化的可以将excel的标题行命名为key,这样会更灵活

注:数据库操作省略,oracle不支持批量插入(可以使用UNION ALL方式,前提是字段值没有序列)



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值