Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Reading Excel Files with Different Headers in Java

Tools 1

Reading Excel Files with Different Headers in Java

In daily work, we often encounter the need to read Excel files and process data. However, sometimes we face Excel files with different headers, requiring us to dynamically read data based on the headers. This article introduces how to read Excel files with different headers using Java and provides code examples.

Excel File Format

First, let's look at the format of Excel files with different headers. Suppose we have two Excel files: one with headers "姓名, 年龄, 性别" and another with headers "Name, Age, Gender".

Reading Excel Files in Java

In Java, we can use the Apache POI library to read Excel files. Below is a simple example code for reading data from an Excel file:

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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExcelReader {

    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream("file.xlsx");
            Workbook workbook = new XSSFWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                for (Cell cell : row) {
                    System.out.print(cell.toString() + "\t");
                }
                System.out.println();
            }

            workbook.close();
            file.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This snippet shows how to read all data from an Excel file. However, to read data based on different headers, we need to dynamically determine the header content.

Reading Data According to Different Headers

To read data based on different headers, we first read the first row of the Excel file and then determine the meening of each column based on that row. Below is an example code that reads data according to headers:

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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExcelReader {

    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream("file.xlsx");
            Workbook workbook = new XSSFWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0);

            Row headerRow = sheet.getRow(0);
            int nameColumnIdx = -1;
            int ageColumnIdx = -1;
            int genderColumnIdx = -1;

            for (Cell cell : headerRow) {
                String cellValue = cell.toString();
                if (cellValue.equals("姓名") || cellValue.equals("Name")) {
                    nameColumnIdx = cell.getColumnIndex();
                } else if (cellValue.equals("年龄") || cellValue.equals("Age")) {
                    ageColumnIdx = cell.getColumnIndex();
                } else if (cellValue.equals("性别") || cellValue.equals("Gender")) {
                    genderColumnIdx = cell.getColumnIndex();
                }
            }

            for (Row row : sheet) {
                String name = row.getCell(nameColumnIdx).toString();
                String age = row.getCell(ageColumnIdx).toString();
                String gender = row.getCell(genderColumnIdx).toString();

                System.out.println(name + "\t" + age + "\t" + gender);
            }

            workbook.close();
            file.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This code first reads the header row, then determines the column indices based on the header values. It then reads data accordingly and outputs it. This allows reading Excel files with different headers.

Summary

In this article, we entroduced how to read Excel files with different headers using Java. By dynamically determining the meaning of each column, we can read data based on different headers. We hope this helps you solve similar problems.

State Diagram

Below is a simple state diagram representing the process of reading Excel files with different headers:

(Note: A state diagram would be displayed here, showing transitions from 'ReadHeader' to 'ParseAndReadData' and back.)

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.