用Java解析Excel文件

用到了Apache的→POI插件←,可点击链接从官网下载,目前已更新至4.0版本

1.将下载好的放入lib(class_path)目录下,

2.编写代码

package com.fyf.test;

import java.io.FileInputStream;

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;

public class PoiRead {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            FileInputStream fStream = new FileInputStream("D:/test.xls");
            Workbook wb = new HSSFWorkbook(fStream);
            Sheet sheet = wb.getSheetAt(0);
            //因为Sheet接口继承了 java.lang.Iterable接口所以,遍历表中的行可以一用foreach很方便    
            for (Row row : sheet) {
          //跳过空行
if (row==null) { continue; } System.out.print("row:"+row.getRowNum()+"\t");
          //同理行中的单元格也可以用foreach遍历
for (Cell cell : row) { if (cell==null) { continue; }
            //对cell进行判断后输出 System.out.print(
"|"+getStringCell(cell)+"\t|"); } System.out.println(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public static String getStringCell(Cell cell) { String result = ""; int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_BOOLEAN: result = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC:
       //这里将数组作为日期返回 result
= String.valueOf(cell.getDateCellValue()); break; case Cell.CELL_TYPE_STRING: result = cell.getStringCellValue(); break; default: break; } return result; } }

 

posted @ 2018-09-18 17:00  annofyf  阅读(4095)  评论(0编辑  收藏  举报