Java implements student information management system to read Excel data

 

Scenario case:

Suppose there is a student information management system that needs to read data such as students' names, ages, and grades from Excel files, and store these data in the system for further processing and management.

 

Specifically, call this function in the data import/export system, and pass in the Excel file as a parameter, and you can get the result containing student information. Then, further processing can be performed on this result, such as storing student data in a database or performing other business logic operations.

 

In the student information management system developed by Java, reading Excel data is a common requirement. Excel files are often used as an input source for student information, so knowing how to read Excel data using Java is a must-have skill for developers. This article will introduce in detail how to use Java to read Excel files and handle exceptions.

 

1. Environmental preparation

 

Before starting, make sure you have installed a Java development environment and understand basic Java syntax. In order to process Excel files, we will use the Apache POI library, which is a popular Java library specifically designed to process Microsoft Office files. If you don't have Apache POI installed, you can add it to your project via Maven or Gradle.

 

2. Code implementation

 

First, we need to import the necessary libraries. In Java, this is usually done with the import statement. Then, we will create a class and define a method to read the Excel file.

 

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.Iterator;

 

Next, we define a method called readExcel that accepts a file path as a parameter and returns a list containing all the student information.

 

public List<Student> readExcel(String filePath) {

    List<Student> students = new ArrayList<>();

    try (FileInputStream fis = new FileInputStream(new File(filePath))) {

        Workbook workbook = new XSSFWorkbook(fis);

        Sheet sheet = workbook.getSheetAt(0); // read the first sheet

        Iterator<Row> rowIterator = sheet.iterator(); // create a row iterator

        while (rowIterator.hasNext()) {

            Row row = rowIterator.next();

            Cell cell = row.getCell(0); // Get the cell in the first column

            String studentName = cell.getStringCellValue();

            students.add(new Student(studentName));

        }

    } catch (IOException e) {

        e.printStackTrace();

    }

    return students;

}

This method first opens the specified Excel file, and then reads each row in the first sheet. For each row, it gets the cell of the first column, and gets the student name from it. Then, it adds this student name to the students list. If an error occurs while reading the file or processing the data, it will print the error stack trace.

 

3. Exception handling

 

When processing files and data, various errors can occur. For example, the file may not exist, or the file may not be an Excel file. Also, the cells may not contain the data we expect. To handle these cases, you should add more error checking and handling code. For example:

 

  1. Check if the file exists: Before opening the file, you can check if the file exists. If the file doesn't exist, you can throw an exception or return an error message.

 

  1. Check if the file is an Excel file: Before opening the file, you can try to read a few bytes of the file and check if they are the signature of the Excel file (eg, "Poi" for the POI library). If not, you can throw an exception or return an error message.

 

  1. Check the data type of the cell: if the cell does not contain a string, then the getStringCellValue method will throw a RuntimeException. You can check the cell's data type using the getCellType method and manipulate the data as needed.

 

4. Handle empty rows: If there is an empty row in the sheet, rowIterator.hasNext() will return false, causing us to stop processing data. You could add a check to make sure each row contains data.

 

4. Practical operation of FuncGPT (wisdom function)

 

Different customized data processing requirements scenarios may have subtle differences in details. It is too cumbersome to write from scratch according to the above tutorial. At this time, developers can think about the general requirements and ask FuncGPT (wit function), and they can still use Apache The POI library quickly realizes the reading of Excel files .

 

Enter requirements:

Read EXCEL data, input parameter: File file, output parameter: List<Map<String, Object>>

 

Click Generate Code to get the complete code.

 

// Class name: ExcelDataReader

// Function name: readExcelData

// Function function: read Excel data and return the result of type List<Map<String, Object>>

// POM dependency package:

// <dependency>

//     <groupId>org.apache.poi</groupId>

//     <artifactId>poi</artifactId>

//     <version>4.1.2</version>

// </dependency>

// <dependency>

//     <groupId>org.apache.poi</groupId>

//     <artifactId>poi-ooxml</artifactId>

//     <version>4.1.2</version>

// </dependency>

 

import org.apache.poi.ss.usermodel.*;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

public class ExcelDataReader {

    /**

     * Read Excel data and return the result of type List<Map<String, Object>>

     * @param file Excel file

     * @return List<Map<String, Object>> result of Excel data

     * @throws IOException Throws IOException when there is an error reading the Excel file

     */

    public static List<Map<String, Object>> readExcelData(File file) throws IOException {

        List<Map<String, Object>> dataList = new ArrayList<>(); // Create a List to store Excel data

 

        FileInputStream fis = new FileInputStream(file); // Create a file input stream

        Workbook workbook = WorkbookFactory.create(fis); // create Workbook object

 

        Sheet sheet = workbook.getSheetAt(0); // Get the first Sheet

        int rowCount = sheet.getLastRowNum(); // Get the number of rows

 

        Row headerRow = sheet.getRow(0); // Get the header row

        int columnCount = headerRow.getLastCellNum(); // Get the number of columns

 

        for (int i = 1; i <= rowCount; i++) { // loop through each row (skip header row)

            Row row = sheet.getRow(i);

            Map<String, Object> rowData = new HashMap<>();

 

            for (int j = 0; j < columnCount; j++) { // traverse each column

                Cell cell = row.getCell(j);

                String columnName = headerRow.getCell(j).getStringCellValue(); // get column name

 

                Object cellValue;

                switch (cell.getCellType()) { // Get the cell value according to the cell type

                    case STRING:

                        cellValue = cell.getStringCellValue();

                        break;

                    case NUMERIC:

                        cellValue = cell.getNumericCellValue();

                        break;

                    case BOOLEAN:

                        cellValue = cell.getBooleanCellValue();

                        break;

                    case FORMULA:

                        cellValue = cell.getCellFormula();

                        break;

                    default:

                        cellValue = null;

                }

 

                rowData.put(columnName, cellValue); // store the column name and cell value into rowData

            }

 

            dataList.add(rowData); // store rowData in dataList

        }

 

        workbook.close(); // Close the Workbook object

        fis.close(); // close the file input stream

 

        return dataList; // return the result of Excel data

    }

}

 

// function example

// read Excel data example

// Input parameters: file, Excel file

// Output parameter: dataList, List<Map<String, Object>> result of Excel data

// call example:

// File file = new File("data.xlsx");

// List<Map<String, Object>> dataList = ExcelDataReader.readExcelData(file);

// System.out.println(dataList);

// Output result: For example, the Excel data is:

// | Name  | Age | Grade |

// |-------|-----|-------|

// | Alice | 18  | A     |

// | Bob   | 20  | B     |

// Then the output result is: [{Name=Alice, Age=18, Grade=A}, {Name=Bob, Age=20, Grade=B}]

// Indicates that the Excel data is encapsulated in the format of List<Map<String, Object>>

 

 

 

FuncGPT (intelligent function) is like an online "famous teacher", which can give you a clear, easy-to-understand, excellent readability, and relatively accurate "solution" according to your needs in a short period of time, even ready-to-use code. In specific demand scenarios, developers can modify the code generated by FuncGPT according to their actual needs.

 

For example, because the overall format content of EXCEL will affect the reading of real data in valid rows or columns, it is necessary to perform relevant valid checks on rows and columns. On the basis of the original code, the following modifications can be made:

 

1) First judge the column, because the real length of the column will affect the reading of the row;

 

2) Read the header of the first row. If a blank column is encountered, the valid column is considered to be the subscript of the previous column.

 

3) After obtaining the valid columns, iterate through the data of each row. If there is an entire row empty, it will jump out of the loop and end the data acquisition.

 

FuncGPT (wit function) is now available for free, download link: https://suo.im/a2pXi

 

V. Summary

 

Through the above code and explanation, we understand how to use Java and Apache POI library to read Excel files. This is very important for developing applications such as student information management systems. At the same time, proper handling of possible exceptions is also an integral part of the development process. Hope this article helps you realize your project.

 

Microsoft's official announcement: Visual Studio for Mac retired The programming language created by the Chinese developer team: MoonBit (Moon Rabbit) Bjarne Stroustrup, the father of C++, shared life advice Linus also dislikes messy abbreviations, what TM is called "GenPD" Rust 1.72.0 released , the minimum supported version in the future is Windows 10 Wenxin Yiyan opens WordPress to the whole society and launches the "100-year plan" . : Crumb green language V1.0 officially released
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4868096/blog/10105886