java怎么读取上传的excel

660
2024/9/26 6:32:16
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,你可以使用Apache POI库或者jxl库来读取上传的Excel文件。这里我将为你提供一个使用Apache POI库的示例。

首先,确保你的项目中已经添加了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文件的第一个工作表,并打印出所有单元格的内容。你可以根据需要修改这个代码来处理其他工作表或者单元格。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java union与数组的差异在哪里