【使用java ssm Excel解析创建数据库批量导入数据库】

这段代码展示了如何使用Java处理Excel文件,解析内容并根据不同的表格类型批量导入数据到SQLite数据库。服务层方法initExceSubject处理文件读取和数据映射,而Controller层进行数据库操作,包括创建表和执行批量插入。代码支持Excel2003和2007格式。
摘要由CSDN通过智能技术生成

最近属实忙的很,也很久没有写blog,既然有点时间就整理一下吧。

额。。。。没时间直接贴代码吧!

使用java ssm Excel解析 创建数据库批量导入

实体类

根据自己的实体字段编写;
后期做改进,自动解析excel第二行自动映射为数据库的字段

service层
ExcelBaseDataService

  public List initExceSubject(File file, String rootPath) throws IOException, SQLException, ClassNotFoundException {
        boolean notNull = false;
        String fileName = String.valueOf(file);
        List<PeijianExcelBean> userList = new ArrayList<>();
        List<FixFreeBean> userList2 = new ArrayList<>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new MyException("上传文件格式不正确");
        }

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        FileInputStream is = new FileInputStream(file);

        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            notNull = true;
        }
        SqliteHelper sqliteHelper = new SqliteHelper(rootPath + GlobalExam.EXCEL_DB_PATH + "/" + excelDataBaseName);



        for (int k= 0; k < 1; k++) {
            Row roww = sheet.getRow(k);
            String rowTable=roww.getCell(0).getStringCellValue();
            //rowTableName=rowTable;
            if (rowTable.equals("配件价格表")) {

                for (int r = 2; r <= sheet.getLastRowNum(); r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    PeijianExcelBean PeijianExcelBean = new PeijianExcelBean();
                    String categoryMax = row.getCell(0).getStringCellValue();
                    String categoryMin = row.getCell(1).getStringCellValue();
                    CellType priceCell= row.getCell(2).getCellTypeEnum();
                    String priceStr = "";

                    if(priceCell==CellType.STRING){
                        priceStr=row.getCell(2).getStringCellValue();

                        PeijianExcelBean.setPrice(priceStr);
                    } else if (priceCell==CellType.NUMERIC){
                        String  price2 = String.valueOf(row.getCell(2).getNumericCellValue());
                        PeijianExcelBean.setPrice(price2);
                    }


                    if (categoryMax.equals("")&&categoryMin.equals("")) {
                        continue;

                    }
                    PeijianExcelBean.setCategoryMax(categoryMax);
                    PeijianExcelBean.setCategoryMin(categoryMin);

                    userList.add(PeijianExcelBean);

                    sqliteHelper.initExcel(userList);
                }
        }else if (rowTable.equals("维修费用表")){

                for (int j = 2; j <= sheet.getLastRowNum(); j++) {
                    Row row = sheet.getRow(j);
                    if (row == null) {
                        continue;
                    }
                    FixFreeBean fixFreeBean=new FixFreeBean();
                    String categoryMax = row.getCell(0).getStringCellValue();
                    String categoryMin = row.getCell(1).getStringCellValue();
                    CellType priceCell= row.getCell(2).getCellTypeEnum();
                    String priceStr = "";

                    if(priceCell==CellType.STRING){
                        priceStr=row.getCell(2).getStringCellValue();

                        fixFreeBean.setPrice(priceStr);
                    } else if (priceCell==CellType.NUMERIC){
                        String  price2 = String.valueOf(row.getCell(2).getNumericCellValue());
                        fixFreeBean.setPrice(price2);
                    }


                    if (categoryMax.equals("")&&categoryMin.equals("")) {
                        continue;

                    }
                    fixFreeBean.setCategoryMax(categoryMax);
                    fixFreeBean.setCategoryMin(categoryMin);

                    userList2.add(fixFreeBean);
                    //logger.info("加载到list等待插入数据库");
                    sqliteHelper.initFixExcel(userList2);
                }

            }else {
                logger.info("请规范excel格式");
            }

            logger.info("解析完成");
        }


        return userList;
    }


controller 调用一下就好了

until 数据库工具实现创建插入数据库

 /*配件*/
    @Transactional
    public void initExcel(List<PeijianExcelBean> subjectList) throws SQLException, ClassNotFoundException {
        try {
            beginTransaction();
            //创建数据库表
            LOGGER.info("开始创建表");
            String createTableSql = "DROP TABLE IF EXISTS \"表\";\n" +
                    "CREATE TABLE \"表\" (\n" +
                    "  \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
                    "  \"category_max\" varchar(20),\n" +
                    "  \"category_min\" varchar(20),\n" +
                    "  \"price\" varchar(10))";

            getStatement().executeUpdate(createTableSql);
            LOGGER.info("成功创建表");
            LOGGER.info("执行导入数据");
            String sql = "INSERT INTO 表(category_max, category_min, price) " +
                    "VALUES ( ?, ?, ?);";
            PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
            for (PeijianExcelBean subject : subjectList) {

                preparedStatement.setString(1, subject.getCategoryMax());
                preparedStatement.setString(2, subject.getCategoryMin());
                preparedStatement.setString(3, subject.getPrice());

                preparedStatement.addBatch();
            }
            int[] updateCounts = preparedStatement.executeBatch();
            LOGGER.info("结束执行导excel数据");
            commitTransaction();
        } finally {
            destroyed();
        }
    }

这个代码是自己记录回忆使用,板书格式很随意。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
连接数据库通常需要以下步骤: 1. 加载数据库驱动程序:使用 Class.forName() 方法加载数据库驱动程序,一般放在程序的初始化部分。 2. 建立数据库连接:使用 DriverManager 类的 getConnection() 方法建立数据库连接,该方法需要提供数据库的 URL、用户名和密码等信息。 3. 执行 SQL 语句:使用建立的数据库连接创建 Statement 对象,并使用该对象的 executeQuery() 或 executeUpdate() 方法执行 SQL 语句。 4. 处理查询结果:对于 SELECT 语句,使用 ResultSet 对象处理查询结果,并进行相应的数据处理或界面展示。 5. 关闭数据库连接:使用 Connection 对象的 close() 方法关闭数据库连接。 下面是一个使用 Java JDBC 连接 MySQL 数据库的示例代码: ```java import java.sql.*; public class JdbcDemo { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // 加载数据库驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 建立数据库连接 String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "123456"; conn = DriverManager.getConnection(url, user, password); // 执行查询语句 stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM users"); // 处理查询结果 while (rs.next()) { System.out.println(rs.getString("name") + "\t" + rs.getInt("age")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { // 关闭数据库连接 try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } ``` 以上代码演示了如何加载 MySQL 驱动程序,建立数据库连接,执行查询语句并处理查询结果,最后关闭数据库连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kokotao

你的鼓励就是的创作的最大动力,

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值