package com.zzsn.knowbase.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class ExcelExportUtil {

    /**
     * 读取excel数据
     *
     * @param firstRow  第一行有用数据(0表示第一行)
     * @param columnNum 有用数据的总列数
     * @return java.util.List<java.util.List < java.lang.String>>
     */
    public static List<List<String>> readExcel(InputStream inputStream, Integer firstRow, Integer columnNum) throws Exception {
        List<List<String>> dataList = new ArrayList<>();
        //获取整个excel
        XSSFWorkbook hb = new XSSFWorkbook(inputStream);
        int sheets = hb.getNumberOfSheets();
        for (int i = 0; i < sheets; i++) {
            XSSFSheet sheet = hb.getSheetAt(i);
            //第一行
            int firstRowNum = sheet.getFirstRowNum();
            //最后一行
            int lastRowNum = sheet.getPhysicalNumberOfRows();
            for (int j = firstRowNum + firstRow; j < lastRowNum; j++) {
                //获取行
                XSSFRow row = sheet.getRow(j);
                if (row != null) {
                    List<String> list = new ArrayList<>();
                    for (int m = 0; m < columnNum; m++) {
                        String data = ExcelExportUtil.getValue(row.getCell(m)).trim();
                        list.add(data);
                    }
                    dataList.add(list);
                }
            }
        }

        return dataList;
    }

    public static String getValue(XSSFCell xssfCell) {
        if (xssfCell == null || xssfCell.toString().trim().equals("")) {
            return "";
        }
        int cellType = xssfCell.getCellType();
        if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
            if (HSSFDateUtil.isCellDateFormatted(xssfCell)) {
                return TimeUtil.getDateString(xssfCell.getDateCellValue());
            } else {
                //防止数字变成科学计数法的形式
                DecimalFormat df = new DecimalFormat("0");
                return df.format(xssfCell.getNumericCellValue());
            }
        } else {
            return xssfCell.getStringCellValue();
        }
    }
}
