以下是Java导入Excel的示例代码:

  1. 使用Apache POI库:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExcelReader {

    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream(new File("path/to/excel/file.xlsx"));
            Workbook workbook = WorkbookFactory.create(file);
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                    case STRING:
                        System.out.print(cell.getRichStringCellValue().getString() + " ");
                        break;
                    case NUMERIC:
                        System.out.print(cell.getNumericCellValue() + " ");
                        break;
                    case BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + " ");
                        break;
                    default:
                        break;
                    }
                }
                System.out.println();
            }

            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用jxl库:
import java.io.File;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

public class ExcelReader {

    public static void main(String[] args) {
        try {
            Workbook workbook = Workbook.getWorkbook(new File("path/to/excel/file.xls"));
            Sheet sheet = workbook.getSheet(0);

            for (int i = 0; i < sheet.getRows(); i++) {
                for (int j = 0; j < sheet.getColumns(); j++) {
                    Cell cell = sheet.getCell(j, i);
                    System.out.print(cell.getContents() + " ");
                }
                System.out.println();
            }

            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意:以上示例代码仅适用于读取Excel文件中的文本、数值和布尔值类型的单元格,如果需要读取其他类型的单元格,需要根据具体情况进行修改

java导入excel代码

原文地址: http://www.cveoy.top/t/topic/eM8D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录