java导入excel表

导入功能


html代码

<div>
   <form enctype="multipart/form-data" id="ssss">
       <input type="file" name="files" id="dr" accept=".xls" style="margin-left: 30px"/>
   <button class="btn" id="entranceInfo">导入</button>
   </form>
   <span id="prompt"></span>
 </div>

js代码

$("#entranceInfo").click(function(){
    event.preventDefault();//可以取消默认的from表单提交
    var formData = new FormData($("#ssss")[0]);
    console.log(formData);
    if($("#dr").val()==null || $("#dr").val()==""){
        createPnotify('error',"请选择Excel文件");
        return;
    }
    $.ajax({
        type: "post",
        url: url,
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function (request) {
            request.setRequestHeader("SESSIONID", localStorage.getItem('sessionId'));
        },
        success: function(result){
            var datas = JSON.parse(result);
            if(datas.code==200){
                $("#prompt").html("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;成功:"+datas.data.success+",失败:"+datas.data.fail+"错误信息:"+(datas.data.prompt).replace(/H/g,"<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));
                infoTable.ajax.reload();
            }else {
                createPnotify('error',datas.msg);
            }
        }
    })
});

后端接口

    @RequestMapping(value = "/suifang/excelImport", method = RequestMethod.POST)
    public void excelImport(@RequestParam("files") MultipartFile files ,HttpServletRequest request,HttpServletResponse response) {
        System.out.println("8888888888888888888888"+files);
        AjaxResponseMessage ajaxResponseMessage = new AjaxResponseMessage(ErrorCode.SYS_SUCCESS, messageUtil.getMessage("process.ok"));
        int success=0;//成功
        int fail=0;//失败
        String prompt="";//错误信息
        String path=" ";//表路径
        try {
            String filename = files.getOriginalFilename();
            String _ext = filename.substring(filename.lastIndexOf("."));
            path= PropertiesUtil.getString("temp.fileExcel.path")+File.separator+ DateUtil.getDays()+File.separator+System.currentTimeMillis()+_ext;
            System.out.println(path);
            FileUtils.writeByteArrayToFile(new File(path), files.getBytes());
            Workbook workbook = Workbook.getWorkbook(new File(path));
            Sheet sheet = workbook.getSheet(0);
            for(int i=1;i<sheet.getRows();i++){
                Cell[] cells = sheet.getRow(i);
                FamliyAccessReq f = new FamliyAccessReq();
                if(cells[0].getContents()!=null){
                    f.setUserName(cells[0].getContents());
                }
                if(cells[1].getContents()!=null){
                    f.setUserMobile(cells[1].getContents());
                }
                if(cells[2].getContents()!=null){
                    f.setSn(cells[2].getContents());
                }
                if("女".equals(cells[3].getContents()) ){
                    f.setGender((byte)1);
                }else {
                    f.setGender((byte)0);
                }
                if(cells[4].getContents()!=null){
                    f.setAddress(cells[4].getContents());
                }
                if("OSA".equals(cells[3].getContents()) ){
                    f.setSnDevice((byte)1);
                }else {
                    f.setSnDevice((byte)2);
                }
                if(cells[6].getContents()!=null){
                    f.setProvince(cells[6].getContents());
                }
                if(cells[7].getContents()!=null){
                    f.setCity(cells[7].getContents());
                }
                f.setKefu_id(1000077l);
                System.out.println(f);
                try {
                    familyAccessService.save(PlatomUtils.getSessionId(request), f);
                    success++;
                }catch (BusinessException businessException) {
                    fail++;
                    prompt+="H第"+i+"行"+f.getUserName()+","+f.getSn()+messageUtil.getMessage("exception.code." + businessException.getCode());
                }catch (Exception e){
                    fail++;
                    prompt+="H第"+i+"行"+f.getUserName()+","+f.getSn()+messageUtil.getMessage("process.error");
                }
            }
            Map<String, String> map = new HashMap<String, String>();
            map.put("success", success+"");
            map.put("fail", fail+"");
            map.put("prompt", prompt);
            ajaxResponseMessage.setData(map);
            workbook.close();
        }catch (Exception e) {
            ajaxResponseMessage.setCode(ErrorCode.SYS_ERROR);
            ajaxResponseMessage.setMsg(messageUtil.getMessage("process.error"));
            printLogger(e);
        } finally {
            new File(path).delete();
        }
        ServletResponseHelper.outUTF8(response, JSON.toJSONString(ajaxResponseMessage));
    }

遇到的问题:
在from表单只设置一个button标签的话,会把button默认设置为提交按钮,并且from表单没有指定路径的话,会自动刷新本网页
解决方法
event.preventDefault();
可以取消表单默认

### Java 实现Excel 导入数据到数据库的接口 #### 使用 Java Excel API 进行操作 Java Excel API 提供了许多用于访问和读取 Excel 文件的功能。通过这些功能,可以轻松地将 Excel 中的数据提取出来并存储到数据库中[^1]。 以下是基于 Java 和 JDBC 的示例代码,展示如何使用 Apache POI 或其他类似的库来解析 Excel 并将其内容插入到数据库: ```java import org.apache.poi.ss.usermodel.*; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class ExcelToDatabase { public static void main(String[] args) { String excelFilePath = "path/to/your/excel/file.xlsx"; String jdbcUrl = "jdbc:mysql://localhost:3306/your_database_name"; String username = "root"; String password = "password"; try (FileInputStream fis = new FileInputStream(excelFilePath); Workbook workbook = WorkbookFactory.create(fis)) { Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作 Connection connection = DriverManager.getConnection(jdbcUrl, username, password); String insertQuery = "INSERT INTO your_table_name (column1, column2, column3) VALUES (?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); for (Row row : sheet) { // 遍历每一行 Cell cell1 = row.getCell(0); Cell cell2 = row.getCell(1); Cell cell3 = row.getCell(2); if (cell1 != null && cell2 != null && cell3 != null) { preparedStatement.setString(1, cell1.getStringCellValue()); preparedStatement.setDouble(2, cell2.getNumericCellValue()); preparedStatement.setString(3, cell3.getStringCellValue()); preparedStatement.addBatch(); // 添加批量执行 } } preparedStatement.executeBatch(); // 执行批量插入 System.out.println("Data inserted successfully!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码展示了如何利用 Apache POI 库加载 Excel 文件,并逐行读取其内容,随后通过 JDBC 将数据插入 MySQL 数据库中[^2]。 #### 性能优化建议 当面对大规模数据(如十万级以上的行数)时,原始的导入方式可能会遇到性能瓶颈。为了提高效率,可以从以下几个方面入手[^3]: - **减少对象创建次数**:避免频繁实例化不必要的对象。 - **批处理模式**:启用 JDBC 的 `addBatch` 方法以减少单次提交的数量。 - **调整 JVM 参数**:增加内存分配比例,确保程序运行期间有足够的堆空间支持大文件解析。 - **索引管理**:在大批量插入前暂时禁用外键约束及非必要索引,完成后重新激活它们。 #### 注意事项 对于生产环境下的部署,还需要考虑异常捕获机制以及事务控制逻辑,从而保障整个流程的安全性和稳定性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值