溫馨提示×

java怎么讀取上傳的excel

小億
81
2024-09-26 04:03:11
欄目: 編程語言

在Java中,你可以使用Apache POI庫或者jxl庫來讀取上傳的Excel文件。這里我將為你提供一個使用Apache POI庫的示例。

首先,確保你的項目中已經(jīng)添加了Apache POI庫的依賴。如果你使用的是Maven,可以在pom.xml文件中添加以下依賴:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

接下來,你可以使用以下代碼來讀取Excel文件:

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;

public class ExcelReader {

    public static void main(String[] args) {
        String filePath = "path/to/your/excel/file.xlsx";
        try {
            readExcel(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readExcel(String filePath) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(new File(filePath));
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0); // 獲取第一個工作表

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

        workbook.close();
        fileInputStream.close();
    }

    private static Object getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return cell.getNumericCellValue();
            case BOOLEAN:
                return cell.getBooleanCellValue();
            default:
                return "";
        }
    }
}

path/to/your/excel/file.xlsx替換為你的Excel文件的實際路徑。這個示例代碼將讀取Excel文件的第一個工作表,并打印出所有單元格的內(nèi)容。你可以根據(jù)需要修改這個代碼來處理其他工作表或者單元格。

0