Java利用POI读取Excel表格

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

读取结果:

1行 0列  Unit1  Hello! PartA
1行 1列  三年级
1行 2列  上册
1行 3列  Unit 1 Part A
1行 4列  Hello, John. I'm Amy.
1行 5列  你好,John。 我是Amy。
1行 6列  WW3/5
2行 0列  Unit1  Hello! PartA
2行 1列  三年级
2行 2列  上册
2行 3列  Unit 1 Part A
2行 4列  Hi, Amy.
2行 5列  你好,Amy。
2行 6列  MM3/3
3行 0列  Unit1  Hello! PartA
3行 1列  三年级
3行 2列  上册
3行 3列  Unit 1 Part A
3行 4列  I have a pencil.
3行 5列  我有一支铅笔。
3行 6列  WW3/6
4行 0列  Unit1  Hello! PartA
4行 1列  三年级
4行 2列  上册
4行 3列  Unit 1 Part A
4行 4列  I have an eraser.
4行 5列  我有一块橡皮。
4行 6列  MM3/11
5行 0列  Unit1  Hello! PartA
5行 1列  三年级
5行 2列  上册
5行 3列  Unit 1 Part A
5行 4列  I have a ruler.
5行 5列  我有一把尺子。
5行 6列  WW3/7
6行 0列  Unit1  Hello! PartA
6行 1列  三年级
6行 2列  上册
6行 3列  Unit 1 Part A
6行 4列  I have a crayon.
6行 5列  我有一支蜡笔。
6行 6列  MM3/8
7行 0列  Unit1  Hello! PartA
7行 1列  三年级
7行 2列  上册
7行 3列  Unit 1 Part A
7行 4列  Me too!
7行 5列  我也有!
7行 6列  WW3/13
8行 0列  Unit1  Hello! PartB
8行 1列  三年级
8行 2列  上册
8行 3列  Unit 1 Part B
8行 4列  Hi, I'm John. What's your name?
8行 5列  你好,我是John。你叫什么名字?
8行 6列  MM3/4
9行 0列  Unit1  Hello! PartB
9行 1列  三年级
9行 2列  上册
9行 3列  Unit 1 Part B
9行 4列  My name's Mike.
9行 5列  我叫Mike。
9行 6列  MM3/20
10行 0列  Unit1  Hello! PartB
10行 1列  三年级
10行 2列  上册
10行 3列  Unit 1 Part B
10行 4列  Look! I have a bag.
10行 5列  看!我有一个书包。
10行 6列  MM3/19
11行 0列  Unit1  Hello! PartB
11行 1列  三年级
11行 2列  上册
11行 3列  Unit 1 Part B
11行 4列  I have a pencil box.
11行 5列  我有一个铅笔盒。
11行 6列  MM3/10
12行 0列  Unit1  Hello! PartB
12行 1列  三年级
12行 2列  上册
12行 3列  Unit 1 Part B
12行 4列  I have a pen.
12行 5列  我有一支钢笔。
12行 6列  MM3/9
13行 0列  Unit1  Hello! PartB
13行 1列  三年级
13行 2列  上册
13行 3列  Unit 1 Part B
13行 4列  I have a book.
13行 5列  我有一本书。
13行 6列  MM3/7
14行 0列  Unit1  Hello! PartB
14行 1列  三年级
14行 2列  上册
14行 3列  Unit 1 Part B
14行 4列  John and Mike, open your books.
14行 5列  John和Mike,打开你们的书。
14行 6列  WW3 /1
15行 0列  Unit2  Colours PartA
15行 1列  三年级
15行 2列  上册
15行 3列  Unit 2 Part A
15行 4列  Good morning, Sarah.
15行 5列  早上好,Sarah。
15行 6列  MM3/1
16行 0列  Unit2  Colours PartA
16行 1列  三年级
16行 2列  上册
16行 3列  Unit 2 Part A
16行 4列  How are you?
16行 5列  早上好。
16行 6列  WW3/4
17行 0列  Unit2  Colours PartA
17行 1列  三年级
17行 2列  上册
17行 3列  Unit 2 Part A
17行 4列  Sarah, this is Mike.
17行 5列  Sarah,这是Mike。
17行 6列  MM3/24
18行 0列  Unit2  Colours PartA
18行 1列  三年级
18行 2列  上册
18行 3列  Unit 2 Part A
18行 4列  Good morning, Sarah.
18行 5列  早上好,Sarah。
18行 6列  MM3/2
19行 0列  Unit2  Colours PartA
19行 1列  三年级
19行 2列  上册
19行 3列  Unit 2 Part A
19行 4列  This is a rainbow.
19行 5列  这是一道彩虹。
19行 6列  MM3/25
20行 0列  Unit2  Colours PartA
20行 1列  三年级
20行 2列  上册
20行 3列  Unit 2 Part A
20行 4列  Oh, I see red.
20行 5列  哦,我看到了红色。




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值