Java POI 读写Excel 文件简单实现

来源:互联网 发布:mac os x10.11安装 编辑:程序博客网 时间:2024/05/21 22:31

整理FileUtils的一些方法,只是一些初步实现,刚写完就挂上来了…

友情提示:**过于结构化,没太多润色....码的不好还请诸位海涵并多提意见**

关联的类型

资源 类型 说明 Workbook 接口 Excel工作簿的高级表示。这是大多数用户在阅读或编写工作簿时所构建的第一个对象。它也是创建新表/等的顶级对象 WorkbookFactory 类 创建合适的工作簿(HSSFWorkbook或XSSFWorkbook),从提供的输入中自动检测。 HSSFWorkbook 类 .xls (97版和2003版的格式) XSSFWorkbook 类 .xlsx (2007之后版本格式) Sheet 接口 Excel工作表的高级表示。表是工作簿中的中心结构,并且是用户在其电子表格中工作的地方。最常见的表类型是工作表,它表示为单元格网格。工作表单元格可以包含文本、数字、日期和公式。单元格也可以被格式化。 Row 接口 行 Cell 接口 单元格

如果有其他需求可参考官方文档:http://poi.apache.org/apidocs/index.html?overview-summary.html

jar包预览:这里写图片描述


下载地址:http://download.csdn.net/detail/u013591605/9898273


概述

  1. 读取:
    利用WorkbookFactory 构建一个Workbook对象,按次生成Sheet[1…255]03版,[1…n]07版.根据数据源容器(size)创建对应行(row)的个数rowNumber = size+1(保留一个title),可以理解为一个row代表一个Object,而对应行(row)所包含的单元格(Cell)就是Object的成员属性.
  2. 写入:
    与读取方法不同的事,写入根据实际需求决定是哪种文件格式,另外Cell.setCellStyle()可以定义单元格的外观,换句话说,写入的时候如果将写入的数据只是作为一般存储,也没必要纠结于样式.
  3. Excel 提供的6中参数类型:
Tag 说明 Cell.CELL_TYPE_STRING 代表文本 Cell.CELL_TYPE_BLANK 空白格 Cell.CELL_TYPE_BOOLEAN: 布尔型 Cell.CELL_TYPE_NUMERIC 数字 Cell.CELL_TYPE_ERROR 错误 Cell.CELL_TYPE_FORMULA 公式

代码部分

读取Excel文件

public static <T> Map<String, List<? extends T>> readExcel(String path, Class clzz) {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        List<T> list = new LinkedList<T>();         Map<String, List<? extends T>> map = new HashMap<String, List<? extends T>>();        File file = new File(path);        FileInputStream fis = null;        Workbook workBook = null;        if (file.exists()) {            try {                fis = new FileInputStream(file);                workBook = WorkbookFactory.create(fis);                int numberOfSheets = workBook.getNumberOfSheets();                for (int s = 0; s < numberOfSheets; s++) { // sheet工作表                    Sheet sheetAt = workBook.getSheetAt(s);//                  String sheetName = sheetAt.getSheetName(); //获取工作表名称                    int rowsOfSheet = sheetAt.getPhysicalNumberOfRows(); // 获取当前Sheet的总列数                    System.out.println("当前表格的总行数:" + rowsOfSheet);                    for (int r = 0; r < rowsOfSheet; r++) { // 总行                        Row row = sheetAt.getRow(r);                        if (row == null) {                            continue;                        } else {                            int rowNum = row.getRowNum();                            System.out.println("当前行:" + rowNum);                            int numberOfCells = row.getPhysicalNumberOfCells();                            for (int c = 0; c < numberOfCells; c++) { // 总列(格)                                Cell cell = row.getCell(c);                                if (cell == null) {                                    continue;                                } else {                                    int cellType = cell.getCellType();                                    switch (cellType) {                                    case Cell.CELL_TYPE_STRING: // 代表文本                                        String stringCellValue = cell.getStringCellValue();                                        System.out.print(stringCellValue + "\t");                                        break;                                    case Cell.CELL_TYPE_BLANK: // 空白格                                        String stringCellBlankValue = cell.getStringCellValue();                                        System.out.print(stringCellBlankValue + "\t");                                        break;                                    case Cell.CELL_TYPE_BOOLEAN: // 布尔型                                        boolean booleanCellValue = cell.getBooleanCellValue();                                        System.out.print(booleanCellValue + "\t");                                        break;                                    case Cell.CELL_TYPE_NUMERIC: // 数字||日期                                        boolean cellDateFormatted = DateUtil.isCellDateFormatted(cell);                                        if (cellDateFormatted) {                                            Date dateCellValue = cell.getDateCellValue();                                            System.out.print(sdf.format(dateCellValue) + "\t");                                        } else {                                            double numericCellValue = cell.getNumericCellValue();                                            System.out.print(numericCellValue + "\t");                                        }                                        break;                                    case Cell.CELL_TYPE_ERROR: // 错误                                        byte errorCellValue = cell.getErrorCellValue();                                        System.out.print(errorCellValue + "\t");                                        break;                                    case Cell.CELL_TYPE_FORMULA: // 公式                                        int cachedFormulaResultType = cell.getCachedFormulaResultType();                                        System.out.print(cachedFormulaResultType + "\t");                                        break;                                    }                                }                            }                            System.out.println(" \t ");                        }                        System.out.println("");                    }                }                if (fis != null) {                    fis.close();                }            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        } else {            System.out.println("文件不存在!");        }        return map;    }

写入Excel

@SuppressWarnings("resource")    public static <T> void writeExcel(String path, List<T> list, Class<T> clzz) {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        Field[] declaredFields = clzz.getDeclaredFields();        File file = new File(path);        FileOutputStream fos = null;        Workbook workbook = null;        try {            if (file.exists()) {                fos = new FileOutputStream(file);                String suffix = getSuffix(path);                if (suffix.equalsIgnoreCase("XLSX")) {                    workbook = new XSSFWorkbook();                } else if (suffix.equalsIgnoreCase("XLS")) {                    workbook = new HSSFWorkbook();                } else {                    throw new Exception("当前文件不是excel文件");                }                Sheet sheet = workbook.createSheet(); // 生成工作表                Row row = sheet.createRow(0);                for (int m = 0; m < declaredFields.length; m++) { // 设置title                    Field field = declaredFields[m];                    field.setAccessible(true);                    Cell cell = row.createCell(m);                    String name = field.getName();                    cell.setCellType(Cell.CELL_TYPE_STRING);                    cell.setCellValue(name);                }                for (int i = 0; i < list.size(); i++) { // 数据                    T instance = list.get(i);                    row = sheet.createRow(i + 1);                    for (int j = 0; j < declaredFields.length; j++) {                        Field field = declaredFields[j];                        Object value = field.get(instance);                        String fieldTypeName = field.getGenericType().getTypeName();                        field.setAccessible(true);                        Cell cell = row.createCell(j);                        switch (fieldTypeName) {// content                        case "long":                            double d = Double.valueOf(value.toString());                            cell.setCellValue(d);                            break;                        case "float":                            CellStyle floatStyle = workbook.createCellStyle();                            short format = workbook.createDataFormat().getFormat(".00");// 保留2位精度                            floatStyle.setDataFormat(format);                            double d1 = Double.parseDouble(String.valueOf(value));                            cell.setCellStyle(floatStyle);                            cell.setCellValue(d1);                            break;                        case "int":                            double d2 = Double.parseDouble(String.valueOf(value));                            cell.setCellValue(d2);                            break;                        case "java.util.Date":                            CellStyle dateStyle = workbook.createCellStyle();                            short df = workbook.createDataFormat().getFormat("yyyy-mm-dd");                            dateStyle.setDataFormat(df);                            cell.setCellStyle(dateStyle);                            String format2 = sdf.format(value);                            Date date = sdf.parse(format2);                            cell.setCellValue(date);                            break;                        case "java.lang.String":                            cell.setCellValue(value.toString());                            break;                        }                    }                    workbook.write(fos);                }            } else {                if (file.createNewFile()) {                    writeExcel(path, list, clzz);                } else {                    System.out.println("创建Excel表格失败!");                }            }            if (fos != null) {                fos.close();            }        } catch (Exception e) {            e.printStackTrace();        }    }

截取文件后缀

public static String getSuffix(String path) {        String substring = path.substring(path.lastIndexOf(".") + 1);        return substring;    }

初步实现大概就是这样,还有很多不完善的地方:

  1. 比如数据类型对应(本人用的校验不完善);
  2. 还有就是读写效率与性能优化;
  3. 数据同步,避免脏读脏写;
  4. 其它的以后补充…

原创粉丝点击