Java implements student information management system: a practical method to extract data from Excel

Implementing a student information management system in Java and reading data from Excel usually applies to the following scenarios:

Data Migration and Integration: If you have an existing student information management system, that system may use a database or other storage method, but you want to migrate this data to a new system. Excel files may provide a convenient way to migrate this data because the Excel file format is easy to view and edit.

Data Import: If you are developing a new student information management system, you may need to import student information from other sources. Excel files may be an easy format to obtain and use, especially when the data is already in an Excel file.

Data Analysis: If you need to perform statistical analysis or visualization of student information, Excel files may be a good starting point. You can use Java programs to read Excel files and then process and analyze the data.

Simplify data entry: In some cases, students or faculty may prefer to use an Excel spreadsheet to enter data rather than going through a complex online form or interface. Java programs can read these Excel files and import them into a database or system.

Integration with other systems: If there is an external system or service (such as a financial system or a student achievement service) that already uses data in Excel format, a Java program can integrate the data by reading these Excel files.

Backup and Restore: In some cases, exporting data to an Excel file can be a convenient backup strategy. Likewise, in case of system failure or data loss, data can be recovered from these Excel files.

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. To process Excel files, we will use the Apache POI library, which is a popular Java library designed specifically for processing Microsoft Office files. If you don't have Apache POI installed yet, you can add it to your project via Maven or Gradle.

2. Code implementation

By asking FuncGPT (Function Function), you can still quickly read Excel files by using the Apache POI library.

Enter requirements:

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

Click Generate Code to get the complete code.

// 类名:ExcelDataReader

// 函数名:readExcelData

// 函数功能:读取Excel数据并返回List<Map<String, Object>>类型的结果

// POM依赖包:

// <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 {

    /**

     * 读取Excel数据并返回List<Map<String, Object>>类型的结果

     * @param file Excel文件

     * @return Excel数据的List<Map<String, Object>>结果

     * @throws IOException 当读取Excel文件出现错误时抛出IOException

     */

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

        List<Map<String, Object>> dataList = new ArrayList<>(); // 创建存储Excel数据的List

        FileInputStream fis = new FileInputStream(file); // 创建文件输入流

        Workbook workbook = WorkbookFactory.create(fis); // 创建Workbook对象

        Sheet sheet = workbook.getSheetAt(0); // 获取第一个Sheet

        int rowCount = sheet.getLastRowNum(); // 获取行数

        Row headerRow = sheet.getRow(0); // 获取标题行

        int columnCount = headerRow.getLastCellNum(); // 获取列数

        for (int i = 1; i <= rowCount; i++) { // 遍历每一行(跳过标题行)

            Row row = sheet.getRow(i);

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

            for (int j = 0; j < columnCount; j++) { // 遍历每一列

                Cell cell = row.getCell(j);

String columnName = headerRow.getCell(j).getStringCellValue(); // 获取列名

Object cellValue;

switch (cell.getCellType()) { // 根据单元格类型获取单元格值

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); // 将列名和单元格值存入rowData

}

dataList.add(rowData); // 将rowData存入dataList

}

workbook.close(); // 关闭Workbook对象

fis.close(); // 关闭文件输入流

return dataList; // 返回Excel数据的结果

}

}

// 函数示例

// 读取Excel数据示例

// 入参:file,Excel文件

// 出参:dataList,Excel数据的List<Map<String, Object>>结果

// 调用示例:

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

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

// System.out.println(dataList);

// 输出结果:例如,Excel数据为:

// | Name  | Age | Grade |

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

// | Alice | 18  | A     |

// | Bob   | 20  | B     |

// 则输出结果为:[{Name=Alice, Age=18, Grade=A}, {Name=Bob, Age=20, Grade=B}]

// 表示Excel数据被封装为List<Map<String, Object>>的格式

3. Exception handling

Various errors can occur while processing files and data. For example, the file may not exist, or the file may not be an Excel file. Additionally, cells may not contain the data we expect. To handle these situations, more error checking and handling code should be added. For example:

1. Check whether the file exists: Before opening the file, you can check whether the file exists. If the file does not exist, you can throw an exception or return an error message.

2. 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 (for example, "Poi" for the POI library). If not, you can throw an exception or return an error message.

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

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

FuncGPT is like an online "famous teacher" who can provide you with a clear, easy-to-understand, readable, and relatively accurate "solution" based on your needs in a short period of time. It can even be used right out of the box. code. In specific demand scenarios, developers can make modifications based on the code generated by FuncGPT (Hui Function) according to their actual needs.

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

Google donated $1 million to the Rust Foundation to improve the interoperability between Rust and C++. The web engine project "Servo", which was abandoned by Mozilla, will be reborn in 2024. The father of the Go language summarizes the success factors: the mascot is indispensable jQuery 4.0 .0 beta released open source daily: "Small but beautiful" Tauri has supported Android and iOS; Apple's open source Pkl Google Bard was renamed Gemini, free independent APP Vite 5.1 was officially released, front-end construction tool gallery system PicHome 2.0.1 released Java tool set Hutool-5.8.26 is released, I wish you all the best. The large open source model MaLA-500 is released, supporting 534 languages.
{{o.name}}
{{m.name}}

Guess you like

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