package com.lemon.json;

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

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @program: Lemon
 * @description:
 * @author: ray
 * @create: 2022-09-22 10:24
 **/
public class POIDemo {
    /*
     * 读：
     * 1、打开Excel
     * 2、选择sheet
     * 3、读取行
     * 4、读取列
     * 5、修改内容
     * 6、回写Excel
     * */
    public static void main(String[] args) throws IOException, InvalidFormatException {
        FileInputStream fis = new FileInputStream("src/test/resources/睿思选题.xls");
        // Factory 创建xx类的。workbook等于整个Excel
        Workbook workbook = WorkbookFactory.create(fis);
        // 获取第一个sheet页
        Sheet sheet = workbook.getSheetAt(0);
        // 获取最后一行。使用普通for和增强for循环
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 0; i <= lastRowNum; i++) {
            // 获取行
            Row row = sheet.getRow(i);
            short lastCellNum = row.getLastCellNum();
            for (int j = 0; j < lastCellNum; j++) {
                // 获取单元格
                Cell cell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                // 将单元格数据转为String类型
                cell.setCellType(CellType.STRING);
                // 修改单元格
//                cell.setCellValue("3000");
                // 回写
//                FileOutputStream fos = new FileOutputStream("src/test/resources/测试用例.xls");
//                workbook.write(fos);
                //获取单元格数据
                String value = cell.getStringCellValue();
                System.out.print(value + " ");
            }
            System.out.println();
        }
        //关流
        fis.close();
    }

}
