• ImportExcelUtil 导入excel表格数据转换为对象存储


    package com.lhb.utils;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.text.DecimalFormat;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.logging.Logger;
    
    import com.lhb.service.wk.dto.SjbcExcelDTO;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    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;
    
    /**
     * excel文件上传Util
     *
     * @author lbx
     */
    public class ImportExcelUtil {
        private static Logger log = Logger.getLogger(String.valueOf(ImportExcelUtil.class));
    
        private final static String excel2003L = ".xls"; // 2003- 版本的excel
        private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel
    
        /**
         * 将流中的Excel数据转成List<Map>
         *
         * @param in       输入流
         * @param fileName 文件名(判断Excel版本)
         * @return
         * @throws Exception
         */
        public static List<SjbcExcelDTO> parseExcel(InputStream in, String fileName) throws Exception {
            // 根据文件名来创建Excel工作薄
            Workbook work = getWorkbook(in, fileName);
            if (null == work) {
                throw new Exception("创建Excel工作薄为空!");
            }
            Sheet sheet = null;
            Row row = null;
            Cell cell = null;
            // 返回数据
            List<SjbcExcelDTO> allList = new ArrayList<>();
            // 遍历Excel中所有的sheet
            for (int i = 0; i < work.getNumberOfSheets(); i++) {
                sheet = work.getSheetAt(i);
                if (sheet == null) {
                    continue;
                }
                // 取第一行标题
                row = sheet.getRow(2);
                String title[] = null;
                if (row != null) {
                    title = new String[row.getLastCellNum()];
                    for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                        cell = row.getCell(y);
                        title[y] = (String) getCellValue(cell);
                    }
                } else {
                    continue;
                }
                // 遍历当前sheet中的所有行
                for (int j = 3; j < sheet.getLastRowNum() + 1; j++) {
                    row = sheet.getRow(j);
                    if (!getCellValue(row.getCell(0)).equals("")) {
                        SjbcExcelDTO sjbcExcelDTO = new SjbcExcelDTO();
                        // 遍历所有的列
                        for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                            cell = row.getCell(y);
                            String key = title[y];
                            if (key.equals("位置") && !getCellValue(cell).equals("")) {
                                sjbcExcelDTO.setBcName(getCellValue(cell));
                            }
                            if (key.equals("出勤
    时间") && !getCellValue(cell).equals("")) {
                                sjbcExcelDTO.setCqTime(getCellValue(cell));
                            }
                            if (key.equals("退勤时间") && !getCellValue(cell).equals("")) {
                                sjbcExcelDTO.setTqTime(getCellValue(cell));
                            }
                        }
                        allList.add(sjbcExcelDTO);                }
                }
            }
            work.close();
            return allList;
        }
    
        /**
         * 描述:根据文件后缀,自适应上传文件的版本
         *
         * @param inStr ,fileName
         * @return
         * @throws Exception
         */
        public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
            Workbook wb = null;
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            if (excel2003L.equals(fileType)) {
                wb = new HSSFWorkbook(inStr); // 2003-
            } else if (excel2007U.equals(fileType)) {
                wb = new XSSFWorkbook(inStr); // 2007+
            } else {
                throw new Exception("解析的文件格式有误!");
            }
            return wb;
        }
    
        /**
         * 描述:对表格中数值进行格式化
         *
         * @param cell
         * @return
         */
        public static String getCellValue(Cell cell) {
            String value = null;
            DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
            SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DecimalFormat df2 = new DecimalFormat("0"); // 格式化数字
    
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    value = cell.getRichStringCellValue().getString();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                        value = df.format(cell.getNumericCellValue());
                    } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                        value = sdf.format(cell.getDateCellValue());
                    } else {
                        //Sun Dec 31 15:03:00 CST 1899格式化时间15:03
                        value = sdf2.format(cell.getDateCellValue()).substring(11, 16);
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    //value = cell.getBooleanCellValue();
                    value = "";
                    break;
                case Cell.CELL_TYPE_BLANK:
                    value = "";
                    break;
                default:
                    break;
            }
            return value;
        }
    
        public static void main(String[] args) throws Exception {
            File file = new File("C:\Users\Administrator\Desktop\ylk\cd-project\项目导入表格,修改后格式\司机位置图.xlsx");
            FileInputStream fis = new FileInputStream(file);
            List<SjbcExcelDTO> ls = parseExcel(fis, file.getName());
    
        }
    }
    
    

    //转换目标对象SjbcExcelDTO

    package com.lhb.service.wk.dto;
    
    import cn.afterturn.easypoi.excel.annotation.Excel;
    import lombok.Data;
    
    import java.util.Date;
    
    @Data
    public class SjbcExcelDTO {
    
        /**位置*/
        private String bcName;
        /**出勤时间*/
        private String cqTime;
        /**退勤时间*/
        private String tqTime;
    }
    

    //导入表格的样式,只导入,位置,出勤时间,退勤时间,这三列数据,表格有多个sheet

    //导入成功后的数据列表,和对象信息

  • 相关阅读:
    How to: Display a List of Non-Persistent Objects in a Popup Dialog 如何:在弹出对话框中显示非持久化对象列表
    How to: Use XPO Upcasting in XAF 如何:在 XAF 中使用 XPO 强制转换
    How to: Use the Entity Framework Data Model Located in an External Assembly 如何:使用位于外部程序集中的EF数据模型
    How to: Use the Entity Framework Code First in XAF 如何:在 XAF 中使用EF CodeFirst
    How to: Supply Initial Data for the Entity Framework Data Model 如何:为EF数据模型提供初始数据
    How to: Calculate a Property Value Based on Values from a Detail Collection 如何:基于详细信息集合中的值计算属性值
    How to: Use the Entity Framework Model First in XAF 如何:在 XAF 中使用EF ModelFirst
    How to: Change the Format Used for the FullAddress and FullName Properties 如何:更改用于FullAddress和FullName属性的格式
    How to: Create a Business Model in the XPO Data Model Designer 如何:在 XPO 数据模型设计器中创建业务模型
    How to: Initialize Business Objects with Default Property Values in Entity Framework 如何:在EF中用默认属性值初始化业务对象
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13300606.html
Copyright © 2020-2023  润新知