Java-Excel工具类


package com.minerva.stresstest.common.util;

import com.minerva.stresstest.objs.dataobject.HumitureDO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 
 * @date 2022/9/2
 */
public class ParserExcelUtil {
    private Workbook workbook;

    public ParserExcelUtil() {
    }

    public ParserExcelUtil(File excelFile) throws IOException {
        try {
            this.workbook = new XSSFWorkbook(new FileInputStream(excelFile));
        } catch (Exception var3) {
            this.workbook = new HSSFWorkbook(new FileInputStream(excelFile));
        }
    }

    public ParserExcelUtil(InputStream in) throws IOException {
        try {
            this.workbook = new XSSFWorkbook(in);
        } catch (Exception var3) {
            this.workbook = new HSSFWorkbook(in);
        }
    }
    
    public static List<List<CellValue>> listCellValueList(File file) {
        try (InputStream is = FileUtils.openInputStream(file)){
            return listCellValueList(file.getName(), is, 0, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<List<CellValue>> listCellValueList(File file, Integer sheetNumber, Integer skipRows) {
        try (InputStream is = FileUtils.openInputStream(file)){
            return listCellValueList(file.getName(), is, sheetNumber, skipRows);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    
    public static List<List<CellValue>> listCellValueList(String fileName, InputStream is) throws IOException {
        return listCellValueList(fileName, is, 0, 1);
    }

    /**
     * 解析excel数据
     * @param is
     * @return
     */
    public static List<List<CellValue>> listCellValueList(String fileName, InputStream is, Integer sheetNumber, Integer skipRows) throws IOException {
        try {
            List<List<ParserExcelUtil.CellValue>> rowDatas;
            if ("xls".equals(fileName.substring(fileName.lastIndexOf(".") + 1))) {
                ParserExcelUtil parserExcelUtil = new ParserExcelUtil();
                parserExcelUtil.excel2003SheetParser(is);
                rowDatas = parserExcelUtil.getDatasInSheet2CellValue(sheetNumber, skipRows);
            } else {
                rowDatas = new ParserExcelUtil(is).getDatasInSheet2CellValue(sheetNumber, skipRows);
            }
            return rowDatas;
        } catch (Exception e) {
            throw new IOException("解析excel失败");
        }
    }

    /**
     * 实例化解析对象。
     *
     * @param in
     *            待解析的文件流。
     * @throws IOException
     */
    public void excel2003SheetParser(InputStream in) throws IOException {
        try {
            workbook = new HSSFWorkbook(in);
        }catch (Exception e){
            workbook = new XSSFWorkbook(in);

        }
    }
    
    /**
     * 实例化解析对象。
     *
     * @param in
     *            待解析的文件流。
     * @throws IOException
     */
    public void excel2007SheetParser(InputStream in) throws IOException {
        workbook = new XSSFWorkbook(in);
    }
    
    /**
     * 根据所提供的文件解析成java的数据集合。
     *
     * @param sheetNumber
     *            excel里的sheet,从0开始
     * @param skipRows
     *            假如有头部信息,需要指定跳过头几行。
     * @return 数据的集合。
     */
    public List<List<CellValue>> getDatasInSheet2CellValue(int sheetNumber, int skipRows) {

        List<List<CellValue>> result = new ArrayList<List<CellValue>>();

        // 获取指定的sheet
        Sheet sheet = workbook.getSheetAt(sheetNumber);

        int rowCount = sheet.getLastRowNum();
        //获取第一个画布

        CellReference cellReference = new CellReference("A4");
        boolean flag = false;
        for (int i = cellReference.getRow(); i <= sheet.getLastRowNum();) {
            Row r = sheet.getRow(i);
            if(r == null){
                //如果是空行(即没有任何数据、格式),直接把它以下的数据往上移动
                sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
                continue;
            }
            flag = false;
            for(Cell c : r){
                if(c.getCellType() != Cell.CELL_TYPE_BLANK){
                    flag = true;
                    break;
                }
            }
            if(flag){
                i++;
                continue;
            }else{//如果是空白行(即可能没有数据,但是有一定格式)
                if(i == sheet.getLastRowNum()){
                    //如果到了最后一行,直接将那一行remove掉
                    sheet.removeRow(r);
                }else{
                    //如果还没到最后一行,则数据往上移一行
                    sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
                }
            }
        }

        System.out.println("有效行数:"+(sheet.getLastRowNum()));
        rowCount=sheet.getLastRowNum();
        int rowIndex = skipRows == 0 ? sheet.getFirstRowNum() : skipRows;

        if (rowCount < 1) {
            return result;
        }

        for (; rowIndex <= rowCount; rowIndex++) {
            Row row = sheet.getRow(rowIndex);

            if (row != null) {
                List<CellValue> rowData = new ArrayList<CellValue>();
                int columnCount = row.getLastCellNum();
                int columnIndex = row.getFirstCellNum();

                for (; columnIndex < columnCount; columnIndex++) {
                    Cell cell = row.getCell(columnIndex);
                    if (cell!=null){
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                    }
                    Object cellStr = this.getCellString(cell);
                    if(cell!=null&&!"".equals(cell)&&!"".equals(cell.getStringCellValue())){
                        CellValue cellvalue = new CellValue(columnIndex, cellStr);
                        rowData.add(cellvalue);
                    }
                    //CellValue cellvalue = new CellValue(columnIndex, cell.getStringCellValue());
                }
                result.add(rowData);
            }
        }
        return result;
    }

    private Object getCellString(Cell cell) {
        Object result = null;
        if (null == cell) {
            return null;
        }
//		cell.setCellType(Cell.CELL_TYPE_STRING);
        if (null != cell) {
            int cellType = cell.getCellType();
            switch (cellType) {
                case Cell.CELL_TYPE_STRING:
                    result = cell.getRichStringCellValue().getString();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    result = getNumbericValue2String(cell);
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    result = getNumbericValue2String(cell);
                    break;
                case Cell.CELL_TYPE_ERROR:
                    result = "";
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    result = cell.getBooleanCellValue();
                    break;
                case Cell.CELL_TYPE_BLANK:
                    result = "";
                    break;
                default:
                    result = "";
            }
        }
        return result;
    }

    //处理科学计数法
    private String getNumbericValue2String(Cell cell){

//        cell.setCellType(Cell.CELL_TYPE_STRING);


        if(HSSFDateUtil.isCellDateFormatted(cell)){
//用于转化为日期格式

            Date d = cell.getDateCellValue();

            DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String format = formater.format(d);
            return format;

        }else{
            DecimalFormat df = new DecimalFormat("0.00");
            String whatYourWant = df.format(cell.getNumericCellValue());
            return whatYourWant;
        }
    }

    /**
     * 获取工作簿名称
     */
    public String getSheetName(Integer index)throws IOException {
        String sheetName = workbook.getSheetAt(index).getSheetName();
        return sheetName;
    }

    public class CellValue{
        private int index;

        private Object value;

        private CellValue() {
            super();
        }

        private CellValue(int index, Object value) {
            super();
            this.index = index;
            this.value = value;
        }


        public int getIndex() {
            return index;
        }


        public void setIndex(int index) {
            this.index = index;
        }


        public Object getValue() {
            return value;
        }


        public void setValue(Object value) {
            this.value = value;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的Java导出Excel工具类示例,使用Apache POI库: ``` import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtil { public static void exportDataToExcel(List<MyData> dataList, String filePath) throws IOException { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Data Sheet"); createHeaderRow(sheet); int rowCount = 1; for (MyData data : dataList) { Row row = sheet.createRow(rowCount++); writeDataToRow(data, row); } autosizeColumns(sheet); try (FileOutputStream outputStream = new FileOutputStream(filePath)) { workbook.write(outputStream); } } private static void createHeaderRow(Sheet sheet) { Row headerRow = sheet.createRow(0); CellStyle headerCellStyle = sheet.getWorkbook().createCellStyle(); headerCellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); headerCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); String[] headers = {"ID", "Name", "Age", "Gender"}; for (int i = 0; i < headers.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(headers[i]); cell.setCellStyle(headerCellStyle); } } private static void writeDataToRow(MyData data, Row row) { Cell idCell = row.createCell(0); idCell.setCellValue(data.getId()); Cell nameCell = row.createCell(1); nameCell.setCellValue(data.getName()); Cell ageCell = row.createCell(2); ageCell.setCellValue(data.getAge()); Cell genderCell = row.createCell(3); genderCell.setCellValue(data.getGender()); } private static void autosizeColumns(Sheet sheet) { for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) { sheet.autoSizeColumn(i); } } } ``` 在上面的代码中,我们首先创建一个XSSFWorkbook对象,然后创建一个名为“Data Sheet”的工作表。接下来,我们在工作表中创建一个标题行,并设置单元格样式。然后,我们遍历数据列表并将数据写入每一行。最后,我们自适应每列的宽度,然后将工作簿写入输出流中保存到指定路径。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值