JAVA-POI-读取excel文件

使用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();
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值