JAVA-POI-读取excel文件

版权声明:本文为博主原创文章,转载注明地址:http://blog.csdn.net/wang704987562 https://blog.csdn.net/wang704987562/article/details/81837706

使用Apache POI读取excel文件,兼容.xlsx和.xls
POM

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

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

ExcelTest

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.IOException;

/**
 * @author wzx
 * @time 2018/8/19
 */
public class ExcelTest {

    public static final String SAMPLE_XLSX_FILE_PATH = "D:\\test1.xlsx";

    public static final String SAMPLE_XLSX_FILE_PATH2 = "D:\\test2.xls";

    public static void main(String[] args) throws IOException, InvalidFormatException {
        readExcel();
    }

    public static void readExcel() throws IOException, InvalidFormatException {
        Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH2));
        System.out.println("sheets" + workbook.getNumberOfSheets());
        //获取第一张表
        Sheet sheet = workbook.getSheetAt(0);
        for (Row row : sheet) {
            int index = 0;
            for (Cell cell : row) {
                //读取数据前设置单元格类型
//                cell.setCellType(CellType.STRING);
//                String value = cell.getStringCellValue();
//                System.out.print("value:" + value + " ");

                if(index == 0) {
                    //先设置单元格类型,再读取数据
                    cell.setCellType(CellType.STRING);
                    String value = cell.getStringCellValue();
                    System.out.print("value:" + value + " ");
                }

                if(index == 1) {
                    //先设置单元格类型,再读取数据
                    cell.setCellType(CellType.NUMERIC);
                    Double value = cell.getNumericCellValue();
                    System.out.print("value:" + value + " ");
                }
                index++;
            }
            System.out.println();
        }
    }

}

猜你喜欢

转载自blog.csdn.net/wang704987562/article/details/81837706