java-excel

2022/5/1 20:15:50

本文主要是介绍java-excel,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

import java.io.*;

public class ExcelRead2 {
    public static void main(String[] args) {
        readExcel("D:\\testjavaIO\\test11\\testcase.xlsx","Sheet1");
    }
    //读excel
    public static void readExcel(String excelPath,String sheetName){
        InputStream in = null;
        try {
            File file = new File(excelPath);
            in = new FileInputStream(file);
            Workbook workbook = WorkbookFactory.create(in);
            Sheet sheet = workbook.getSheet(sheetName);
            //获取标题行
            Row firstRow = sheet.getRow(0);
            //获取每行的列数
            int lastCellNum = firstRow.getLastCellNum();
            String[] titles = new String[lastCellNum];
            for (int i = 0; i < lastCellNum; i++) {
                Cell cell = firstRow.getCell(i);
                String title = cell.getStringCellValue();
                titles[i] = title;
            }
            //获取每行测试用例数据
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i < lastRowNum; i++) {
                Row rowDate = sheet.getRow(i);
                System.out.println("第" + i + "行数据:");
                for (int j = 0; j < lastCellNum; j++) {
                    Cell cell = rowDate.getCell(j);
                    if(cell == null){
                        continue;
                    }
                    //设置单元格类型,解决Cannot get a STRING value from a NUMERIC cell报错
                    cell.setCellType(CellType.STRING);
                    String cellValue = cell.getStringCellValue();
                    //打印获取的数据
                    System.out.print("【" + titles[j] + " = " + cellValue + "】");
                }
                System.out.println();
            }
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 



这篇关于java-excel的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程