Làm cách nào để nhập dữ liệu từ Excel vào cơ sở dữ liệu trong Java?

nhấp vào liên kết tôi đã cung cấp, ở đó bạn sẽ tìm thấy mọi phương thức mà lớp đó cung cấp, bao gồm tất cả các phương thức để truy xuất dữ liệu từ nó. chỉ cần xem cái nào bạn không thể sử dụng, sau đó sử dụng cái bạn sẽ có thể sử dụng. tôi đoán. bạn đang tìm kiếm getCellStringValue()

Thử cái này

cố gắng {

        String jdbc_insert_sql = "INSERT INTO TBL_PUNETORET"
                + "( NUMRI_PERSONAL, EMRI_MBIEMRI,DATELINDJA,ADRESA,TELEFONI,DATA_PUNSIMIT,DATA_LARGIMIT,NJESIA,POZITA,TELEFONI_P,EMAIL,PERSHKRIMI,PUNTORI,REKOMANDUAR) "
                + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Class.forName("oracle.jdbc.driver.OracleDriver");

        PreparedStatement preStatement = con.prepareStatement(jdbc_insert_sql);
        con.setAutoCommit(false);

        FileInputStream input = new FileInputStream(filename);
        POIFSFileSystem fs = null;
        try {
            fs = new POIFSFileSystem(input);
        } catch (IOException ex) {
            Logger.getLogger(PunetoretForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        Row row;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            int numripersonal = (int) (row.getCell(0).getNumericCellValue());
            //String numripersonal =  row.getCell(0).getStringCellValue(); 
            String emri = row.getCell(1).getStringCellValue();
            Date datelindja = row.getCell(4).getDateCellValue();
            DateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
            String reportDate = df.format(datelindja);
            df.parse(reportDate);
            String adresa = row.getCell(5).getStringCellValue();
            int telefoni = (int) (row.getCell(6).getNumericCellValue());
            //String telefoni = row.getCell(4).getStringCellValue();
            Date datap = row.getCell(7).getDateCellValue();
            df = new SimpleDateFormat("dd/MMM/yyyy");
            String reportDatap = df.format(datap);
            df.parse(reportDatap);

            Date datal = row.getCell(8).getDateCellValue();
            String ss = null;
            if (datal != null) {
                df = new SimpleDateFormat("dd/MMM/yyyy");
                ss = df.format(datal);
                df.parse(ss);

            }

            String njesia = row.getCell(9).getStringCellValue();
            String pozita = row.getCell(10).getStringCellValue();
            int telp = (int) (row.getCell(11).getNumericCellValue());
            if (telp == 0) {
                String s = String.valueOf(telp);
                s = "Ska numer";
            }
            //String telp = row.getCell(9).getStringCellValue();
            String email = row.getCell(12).getStringCellValue();
            String pershkrimi = row.getCell(13).getStringCellValue();
            String punetori = row.getCell(14).getStringCellValue();
            String rekomanduar = row.getCell(15).getStringCellValue();
            if (datal == null) {
                String sql = "INSERT INTO TBL_PUNETORET ( NUMRI_PERSONAL, EMRI_MBIEMRI,DATELINDJA,ADRESA,TELEFONI,DATA_PUNSIMIT,DATA_LARGIMIT,NJESIA,POZITA,TELEFONI_P,EMAIL,PERSHKRIMI,PUNTORI,REKOMANDUAR) "
                        + "VALUES('" + numripersonal + "','" + emri + "','" + reportDate + "','" + adresa + "','" + telefoni + "','" + reportDatap + "'," + datal + ",'" + njesia + "','" + pozita + "','" + telp + "','" + email + "','" + pershkrimi + "','" + rekomanduar + "','" + punetori + "')";
                preStatement = (PreparedStatement) con.prepareStatement(sql);
                preStatement.execute();
            }

Sau đây là ví dụ về cách nhập tài liệu Excel vào cơ sở dữ liệu MySQL. Để chạy hướng dẫn này, bạn sẽ cần một tệp Excel và quyền truy cập của quản trị viên vào một phiên bản MySQL đang chạy

Ví dụ: chúng tôi sẽ sử dụng tệp Excel sau về thuyền cho thuê

thuyền. xlsx

  1. Mở tệp Excel của bạn và nhấp vào Lưu dưới dạng. Chọn để lưu nó dưới dạng. Tệp CSV (Phân tách bằng dấu phẩy). Nếu bạn đang chạy Excel trên máy Mac, bạn sẽ cần lưu tệp dưới dạng tệp được phân tách bằng dấu phẩy của Windows (. csv) hoặc CSV (Windows) để duy trì định dạng chính xác

    Làm cách nào để nhập dữ liệu từ Excel vào cơ sở dữ liệu trong Java?

    Công nghệ Devstringx

    Làm theo

    Ngày 12 tháng 10 năm 2021

    ·

    2 phút đọc

    Cách nhập dữ liệu excel vào SQLite DB bằng java — Devstringx Technologies

    Nó bao gồm những gì?

    1. Tạo và đóng kết nối cơ sở dữ liệu (JDBC)
    2. Tạo lược đồ động
    3. Tạo bảng và xóa giá trị bảng
    4. Đọc dữ liệu từ excel
    5. Nhập dữ liệu excel vào DB

    điều kiện tiên quyết

    SQLite, Java, Cơ sở dữ liệu

    Làm thế nào nó hoạt động?

    1. Để thực hiện các truy vấn SQL bằng java, chúng ta cần thiết lập kết nối với DB và sau đó tạo một câu lệnh để thực hiện các truy vấn. Sử dụng câu lệnh chuẩn bị để thực hiện câu lệnh nhiều lần
    2. Để tạo lược đồ, chúng tôi đang tạo tổng số cột tối đa có giá trị từ excel
    3. Sử dụng Apache POI để đọc dữ liệu excel và nhập dữ liệu hàng loạt bằng các phương thức câu lệnh đã chuẩn bị
    4. Đóng sổ làm việc và kết nối cơ sở dữ liệu

    Mã số

    // Assign variablesConnection connection = null;PreparedStatement statement = null;Connection connection = null;String dbName = "";String excelFilePath = "";String url = "jdbc:sqlite:" + <"dbPath"> + dbName+ ".db";
    // Create a connection to the database
    connection = DriverManager.getConnection(url);connection.setAutoCommit(false);
    // Opening Worksheet
    FileInputStream inputStream = new FileInputStream(excelFilePath);Workbook workbook = new XSSFWorkbook(inputStream);Sheet firstSheet = workbook.getSheetAt(0); // first sheet
    // Generate maximum number of column in sheet
    int max=0;Iterator rowIterator = firstSheet.iterator();while (rowIterator.hasNext()) {Row nextRow = rowIterator.next();Iterator cellIterator = nextRow.cellIterator();int totalNoOfRows = firstSheet.getLastRowNum(); // To get the number of rows present in sheetwhile (cellIterator.hasNext()) {Cell nextCell = cellIterator.next();int col1 = nextCell.getColumnIndex();for (int row = 1; row <= totalNoOfRows; row++) {if (col1 >= max)max = col1;}}}
    // creating schema
    ArrayList sch = new ArrayList();ArrayList val = new ArrayList();for (int first = 1; first <= max + 1; first++) {sch.add("'" + first + "'");val.add("?");}String schema = sch.toString().replace("[", "(").replace("]", ")").trim();String values = val.toString().replace("[", "(").replace("]", ")").trim();
    // execute queries using create statement
    String table = "CREATE TABLE " + dbName + schema + ";";Statement stmt = connection.createStatement();stmt.executeUpdate(table);String delete = "DELETE FROM " + dbName + ";";Statement stmt = connection.createStatement();stmt.executeUpdate(delete);
    // execute query using prepare statementString insert = "INSERT INTO " + dbName + schema + "VALUES" + values + ";";statement = connection.prepareStatement(insert);

    // Read excel data
    Iterator rowIterator = firstSheet.iterator();while (rowIterator.hasNext()) {int cellCount = 0;Row nextRow = rowIterator.next();ArrayList data = new ArrayList();data.clear();Iterator cellIterator = nextRow.cellIterator();while (cellIterator.hasNext()) {Cell nextCell = cellIterator.next();int col = nextCell.getColumnIndex();if (nextCell.getCellType() == CellType.STRING) {data.add(cellCount, nextCell.getStringCellValue());}else if (nextCell.getCellType() == CellType.NUMERIC) {data.add(cellCount, NumberToTextConverter.toText(nextCell.getNumericCellValue()));}statement.setString(col + 1, data.get(cellCount).toString());cellCount += 1;}
    // Import data in batch using prepared statement methods
    statement.addBatch();statement.executeBatch();statement.clearBatch();}
    // Closing workbook and database connectionworkbook.close();connection.commit();connection.close();

    Được xuất bản lần đầu tại https. //www. devstringx. com vào ngày 07 tháng 10 năm 2021

    Làm cách nào để nhập dữ liệu từ Excel vào cơ sở dữ liệu trong Java?

    table_daily_report();

    Làm cách nào để nhập dữ liệu từ Excel vào cơ sở dữ liệu?

    3. Xuất sang máy chủ SQL .
    Mở SQL Server Management Studio (SSMS) và kết nối với Công cụ cơ sở dữ liệu. .
    Nhấp chuột phải vào Cơ sở dữ liệu và bên dưới Nhiệm vụ, chọn "Nhập dữ liệu". .
    Nhấp vào "Tiếp theo" và chọn "Microsoft Excel" từ menu thả xuống của Nguồn dữ liệu
    Nhấp vào nút "Tiếp theo" và nếu nó phù hợp với bạn, xin chúc mừng

    Làm cách nào để nhập tệp CSV vào cơ sở dữ liệu trong Java?

    Cách tải dữ liệu từ tệp CSV trong Java - Ví dụ .
    Mở tệp CSV bằng đối tượng FileReader
    Tạo BufferedReader từ FileReader
    Đọc từng dòng tệp bằng phương thức readLine()
    Tách từng dòng bằng dấu phẩy để lấy một mảng các thuộc tính bằng Chuỗi. .
    Tạo một đối tượng của lớp Book từ mảng String sử dụng new Book()

    Làm cách nào để đọc dữ liệu từ trang tính Excel và chèn vào bảng cơ sở dữ liệu trong Spring?

    Nếu bạn muốn đọc dữ liệu đầu vào của công việc Spring Batch từ bảng tính Excel, bạn phải thêm các phụ thuộc Spring Batch Excel và Apache POI vào đường dẫn lớp. If you want to read the input data of your batch job by using Spring Batch Excel and Apache POI, you have to use the PoiItemReader class.