Java利用POI读取Excel表格

来源:互联网 发布:黎东方知乎 编辑:程序博客网 时间:2024/05/20 03:42

Maven依赖:一定要注意poi版本与poi-ooxml一定要一致

<!--poi相关开始-->            <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->            <dependency>                <groupId>org.apache.poi</groupId>                <artifactId>poi</artifactId>                <version>3.7</version>            </dependency>            <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->            <dependency>                <groupId>org.apache.poi</groupId>                <artifactId>poi-ooxml</artifactId>                <version>3.7</version>            </dependency>            <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->            <dependency>                <groupId>org.apache.commons</groupId>                <artifactId>commons-collections4</artifactId>                <version>4.0</version>            </dependency>        <!--poi相关结束-->

ExcelUtil工具类:

public class ExcelUtil {    //默认单元格内容为数字时格式    private static DecimalFormat df = new DecimalFormat("0");    // 默认单元格格式化日期字符串    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    // 格式化数字    private static DecimalFormat nf = new DecimalFormat("0.00");    public static ArrayList<ArrayList<Object>> readExcel(File file) {        if (file == null) {            return null;        }        if (file.getName().endsWith("xlsx")) {            //处理ecxel2007            return readExcel2007(file);        } else {            //处理ecxel2003            return readExcel2003(file);        }    }    /*     * @return 将返回结果存储在ArrayList内,存储结构与二位数组类似     * lists.get(0).get(0)表示过去Excel中0行0列单元格     */    public static ArrayList<ArrayList<Object>> readExcel2003(File file) {        try {            ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();            ArrayList<Object> colList;            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));            HSSFSheet sheet = wb.getSheetAt(0);            HSSFRow row;            HSSFCell cell;            Object value;            for (int i = sheet.getFirstRowNum(), rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows(); i++) {                row = sheet.getRow(i);                colList = new ArrayList<Object>();                if (row == null) {                    //当读取行为空时                    if (i != sheet.getPhysicalNumberOfRows()) {//判断是否是最后一行                        rowList.add(colList);                    }                    continue;                } else {                    rowCount++;                }                for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {                    cell = row.getCell(j);                    if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {                        //当该单元格为空                        if (j != row.getLastCellNum()) {//判断是否是该行中最后一个单元格                            colList.add("");                        }                        continue;                    }                    switch (cell.getCellType()) {                        case XSSFCell.CELL_TYPE_STRING:                            System.out.println(i + "行" + j + " 列 is String type");                            value = cell.getStringCellValue();                            break;                        case XSSFCell.CELL_TYPE_NUMERIC:                            if ("@".equals(cell.getCellStyle().getDataFormatString())) {                                value = df.format(cell.getNumericCellValue());                            } else if ("General".equals(cell.getCellStyle()                                    .getDataFormatString())) {                                value = nf.format(cell.getNumericCellValue());                            } else {                                value = sdf.format(HSSFDateUtil.getJavaDate(cell                                        .getNumericCellValue()));                            }                            System.out.println(i + "行" + j                                    + " 列 is Number type ; DateFormt:"                                    + value.toString());                            break;                        case XSSFCell.CELL_TYPE_BOOLEAN:                            System.out.println(i + "行" + j + " 列 is Boolean type");                            value = Boolean.valueOf(cell.getBooleanCellValue());                            break;                        case XSSFCell.CELL_TYPE_BLANK:                            System.out.println(i + "行" + j + " 列 is Blank type");                            value = "";                            break;                        default:                            System.out.println(i + "行" + j + " 列 is default type");                            value = cell.toString();                    }// end switch                    colList.add(value);                }//end for j                rowList.add(colList);            }//end for i            return rowList;        } catch (Exception e) {            return null;        }    }    public static ArrayList<ArrayList<Object>> readExcel2007(File file) {        try {            ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();            ArrayList<Object> colList;            XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(file));            XSSFSheet sheet = wb.getSheetAt(0);            XSSFRow row;            XSSFCell cell;            Object value;            for (int i = sheet.getFirstRowNum(), rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows(); i++) {                row = sheet.getRow(i);                colList = new ArrayList<Object>();                if (row == null) {                    //当读取行为空时                    if (i != sheet.getPhysicalNumberOfRows()) {//判断是否是最后一行                        rowList.add(colList);                    }                    continue;                } else {                    rowCount++;                }                for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {                    cell = row.getCell(j);                    if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {                        //当该单元格为空                        if (j != row.getLastCellNum()) {//判断是否是该行中最后一个单元格                            colList.add("");                        }                        continue;                    }                    switch (cell.getCellType()) {                        case XSSFCell.CELL_TYPE_STRING:                            System.out.println(i + "行" + j + " 列 is String type");                            value = cell.getStringCellValue();                            break;                        case XSSFCell.CELL_TYPE_NUMERIC:                            if ("@".equals(cell.getCellStyle().getDataFormatString())) {                                value = df.format(cell.getNumericCellValue());                            } else if ("General".equals(cell.getCellStyle()                                    .getDataFormatString())) {                                value = nf.format(cell.getNumericCellValue());                            } else {                                value = sdf.format(HSSFDateUtil.getJavaDate(cell                                        .getNumericCellValue()));                            }                            System.out.println(i + "行" + j                                    + " 列 is Number type ; DateFormt:"                                    + value.toString());                            break;                        case XSSFCell.CELL_TYPE_BOOLEAN:                            System.out.println(i + "行" + j + " 列 is Boolean type");                            value = Boolean.valueOf(cell.getBooleanCellValue());                            break;                        case XSSFCell.CELL_TYPE_BLANK:                            System.out.println(i + "行" + j + " 列 is Blank type");                            value = "";                            break;                        default:                            System.out.println(i + "行" + j + " 列 is default type");                            value = cell.toString();                    }// end switch                    colList.add(value);                }//end for j                rowList.add(colList);            }//end for i            return rowList;        } catch (Exception e) {            System.out.println("exception");            return null;        }    }    public static void writeExcel(ArrayList<ArrayList<Object>> result, String path) {        if (result == null) {            return;        }        HSSFWorkbook wb = new HSSFWorkbook();        HSSFSheet sheet = wb.createSheet("sheet1");        for (int i = 0; i < result.size(); i++) {            HSSFRow row = sheet.createRow(i);            if (result.get(i) != null) {                for (int j = 0; j < result.get(i).size(); j++) {                    HSSFCell cell = row.createCell(j);                    cell.setCellValue(result.get(i).get(j).toString());                }            }        }        ByteArrayOutputStream os = new ByteArrayOutputStream();        try {            wb.write(os);        } catch (IOException e) {            e.printStackTrace();        }        byte[] content = os.toByteArray();        File file = new File(path);//Excel文件生成后存储的位置。        OutputStream fos = null;        try {            fos = new FileOutputStream(file);            fos.write(content);            os.close();            fos.close();        } catch (Exception e) {            e.printStackTrace();        }    }    public static DecimalFormat getDf() {        return df;    }    public static void setDf(DecimalFormat df) {        ExcelUtil.df = df;    }    public static SimpleDateFormat getSdf() {        return sdf;    }    public static void setSdf(SimpleDateFormat sdf) {        ExcelUtil.sdf = sdf;    }    public static DecimalFormat getNf() {        return nf;    }    public static void setNf(DecimalFormat nf) {        ExcelUtil.nf = nf;    }}
测试方法:

public class Main {public static void main(String[] args) {File file = new File("E:/anshao/anshao.xlsx");ArrayList<ArrayList<Object>> result = ExcelUtil.readExcel(file);for(int i = 1 ;i < result.size() ;i++){for(int j = 0;j<result.get(i).size(); j++){System.out.println(i+"行 "+j+"列  "+ result.get(i).get(j).toString());}}}}

源文件:

Unit1  Hello! PartA三年级上册Unit 1 Part AHello, John. I'm Amy.你好,John。 我是Amy。WW3/5Unit1  Hello! PartA三年级上册Unit 1 Part AHi, Amy.你好,Amy。MM3/3Unit1  Hello! PartA三年级上册Unit 1 Part AI have a pencil.我有一支铅笔。WW3/6Unit1  Hello! PartA三年级上册Unit 1 Part AI have an eraser.我有一块橡皮。MM3/11Unit1  Hello! PartA三年级上册Unit 1 Part AI have a ruler.我有一把尺子。WW3/7Unit1  Hello! PartA三年级上册Unit 1 Part AI have a crayon.我有一支蜡笔。MM3/8Unit1  Hello! PartA三年级上册Unit 1 Part AMe too!我也有!WW3/13Unit1  Hello! PartB三年级上册Unit 1 Part BHi, I'm John. What's your name?你好,我是John。你叫什么名字?MM3/4Unit1  Hello! PartB三年级上册Unit 1 Part BMy name's Mike.我叫Mike。MM3/20Unit1  Hello! PartB三年级上册Unit 1 Part BLook! I have a bag.看!我有一个书包。MM3/19Unit1  Hello! PartB三年级上册Unit 1 Part BI have a pencil box.我有一个铅笔盒。MM3/10Unit1  Hello! PartB三年级上册Unit 1 Part BI have a pen.我有一支钢笔。MM3/9Unit1  Hello! PartB三年级上册Unit 1 Part BI have a book.我有一本书。MM3/7Unit1  Hello! PartB三年级上册Unit 1 Part BJohn and Mike, open your books.John和Mike,打开你们的书。WW3 /1Unit2  Colours PartA三年级上册Unit 2 Part AGood morning, Sarah.早上好,Sarah。MM3/1Unit2  Colours PartA三年级上册Unit 2 Part AHow are you?早上好。WW3/4Unit2  Colours PartA三年级上册Unit 2 Part ASarah, this is Mike.Sarah,这是Mike。MM3/24Unit2  Colours PartA三年级上册Unit 2 Part AGood morning, Sarah.早上好,Sarah。MM3/2Unit2  Colours PartA三年级上册Unit 2 Part AThis is a rainbow.这是一道彩虹。MM3/25Unit2  Colours PartA三年级上册Unit 2 Part AOh, I see red.哦,我看到了红色。WW3/14Unit2  Colours PartA三年级上册Unit 2 Part AI see yellow.我看到了黄色。MM3/15Unit2  Colours PartA三年级上册Unit 2 Part AI see green and blue.我看到了绿色和蓝色。MM3/13Unit2  Colours PartB三年级上册Unit 2 Part BGood afternoon, Mike.下午好,Mike。WW3/2Unit2  Colours PartB三年级上册Unit 2 Part BHi, Sarah. This is Amy.你好,Sarah。这是Amy。MM3/5Unit2  Colours PartB三年级上册Unit 2 Part BGood afternoon, Sarah. Nice to meet you.下午好,Sarah。见到你很高兴。WW3/3Unit2  Colours PartB三年级上册Unit 2 Part BNice to meet you, too.见到你也很高兴。WW3/11Unit2  Colours PartB三年级上册Unit 2 Part BI have some crayons.我有一些蜡笔。MM3/12Unit2  Colours PartB三年级上册Unit 2 Part BI see black.我看到了黑色。WW3/9Unit2  Colours PartB三年级上册Unit 2 Part BI see white.我看到了白色。WW3/10Unit2  Colours PartB三年级上册Unit 2 Part BI see orange and brown.我看到了橙色和棕色。MM3/14

读取结果:

1行 0列  Unit1  Hello! PartA1行 1列  三年级1行 2列  上册1行 3列  Unit 1 Part A1行 4列  Hello, John. I'm Amy.1行 5列  你好,John。 我是Amy。1行 6列  WW3/52行 0列  Unit1  Hello! PartA2行 1列  三年级2行 2列  上册2行 3列  Unit 1 Part A2行 4列  Hi, Amy.2行 5列  你好,Amy。2行 6列  MM3/33行 0列  Unit1  Hello! PartA3行 1列  三年级3行 2列  上册3行 3列  Unit 1 Part A3行 4列  I have a pencil.3行 5列  我有一支铅笔。3行 6列  WW3/64行 0列  Unit1  Hello! PartA4行 1列  三年级4行 2列  上册4行 3列  Unit 1 Part A4行 4列  I have an eraser.4行 5列  我有一块橡皮。4行 6列  MM3/115行 0列  Unit1  Hello! PartA5行 1列  三年级5行 2列  上册5行 3列  Unit 1 Part A5行 4列  I have a ruler.5行 5列  我有一把尺子。5行 6列  WW3/76行 0列  Unit1  Hello! PartA6行 1列  三年级6行 2列  上册6行 3列  Unit 1 Part A6行 4列  I have a crayon.6行 5列  我有一支蜡笔。6行 6列  MM3/87行 0列  Unit1  Hello! PartA7行 1列  三年级7行 2列  上册7行 3列  Unit 1 Part A7行 4列  Me too!7行 5列  我也有!7行 6列  WW3/138行 0列  Unit1  Hello! PartB8行 1列  三年级8行 2列  上册8行 3列  Unit 1 Part B8行 4列  Hi, I'm John. What's your name?8行 5列  你好,我是John。你叫什么名字?8行 6列  MM3/49行 0列  Unit1  Hello! PartB9行 1列  三年级9行 2列  上册9行 3列  Unit 1 Part B9行 4列  My name's Mike.9行 5列  我叫Mike。9行 6列  MM3/2010行 0列  Unit1  Hello! PartB10行 1列  三年级10行 2列  上册10行 3列  Unit 1 Part B10行 4列  Look! I have a bag.10行 5列  看!我有一个书包。10行 6列  MM3/1911行 0列  Unit1  Hello! PartB11行 1列  三年级11行 2列  上册11行 3列  Unit 1 Part B11行 4列  I have a pencil box.11行 5列  我有一个铅笔盒。11行 6列  MM3/1012行 0列  Unit1  Hello! PartB12行 1列  三年级12行 2列  上册12行 3列  Unit 1 Part B12行 4列  I have a pen.12行 5列  我有一支钢笔。12行 6列  MM3/913行 0列  Unit1  Hello! PartB13行 1列  三年级13行 2列  上册13行 3列  Unit 1 Part B13行 4列  I have a book.13行 5列  我有一本书。13行 6列  MM3/714行 0列  Unit1  Hello! PartB14行 1列  三年级14行 2列  上册14行 3列  Unit 1 Part B14行 4列  John and Mike, open your books.14行 5列  John和Mike,打开你们的书。14行 6列  WW3 /115行 0列  Unit2  Colours PartA15行 1列  三年级15行 2列  上册15行 3列  Unit 2 Part A15行 4列  Good morning, Sarah.15行 5列  早上好,Sarah。15行 6列  MM3/116行 0列  Unit2  Colours PartA16行 1列  三年级16行 2列  上册16行 3列  Unit 2 Part A16行 4列  How are you?16行 5列  早上好。16行 6列  WW3/417行 0列  Unit2  Colours PartA17行 1列  三年级17行 2列  上册17行 3列  Unit 2 Part A17行 4列  Sarah, this is Mike.17行 5列  Sarah,这是Mike。17行 6列  MM3/2418行 0列  Unit2  Colours PartA18行 1列  三年级18行 2列  上册18行 3列  Unit 2 Part A18行 4列  Good morning, Sarah.18行 5列  早上好,Sarah。18行 6列  MM3/219行 0列  Unit2  Colours PartA19行 1列  三年级19行 2列  上册19行 3列  Unit 2 Part A19行 4列  This is a rainbow.19行 5列  这是一道彩虹。19行 6列  MM3/2520行 0列  Unit2  Colours PartA20行 1列  三年级20行 2列  上册20行 3列  Unit 2 Part A20行 4列  Oh, I see red.20行 5列  哦,我看到了红色。