java读取excel文件

来源:互联网 发布:大数据投融资新闻 编辑:程序博客网 时间:2024/05/16 11:13

这段时间,由于工作原因,需要处理好几千条数据,于是从库把数据倒出来,生成的是excel文件。

对于大量重复的操作,人工一个个来处理费时费劲易错,所以就想了搞个程序来处理这些excel里的

数据,于是写了个程序,可以解析excel2007的文档。注:之前用的版本低,报不能错里excel2007

的错误,后面改成poi-3.8就可以支持2007了。如果大家碰到类似的问题,可以升级下版本就ok了。

还有一些经验就是,单excel某列的数值数据查询出来为科学计数法形式,可以根据需要,如Integer类型,

可以讲查出的值扔进Integer的构造函数中,从而实现将科学计数值转为普通的数值,如果某类为空(不是null),

即某列没有数值,poi读取时不会报错,但是读会卡在这里了,一个解决方法就是给这列赋一个null的值,这样

poi就可以继续读取整个excel的数据了。


 以下是我写的一个简单的例子,希望对初次使用的朋友有借鉴之用:

package test;

import java.io.IOException;
import java.util.Date;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 操作Excel表格的功能类
 *
 * @author:hnhychl
 * @version 1.0
 */
public class ExcelReader {

    private static XSSFWorkbook xwb;

    private static XSSFSheet sheet;

    private static XSSFRow row;

    public static void readExcle2007() {
        try {
            xwb = new XSSFWorkbook("c:\\lpk.xlsx");
            sheet = xwb.getSheetAt(0);
            String cell;
            // System.out.println("physical rows = "+ sheet.getPhysicalNumberOfRows());
            // System.out.println("physical cols = "+ sheet.getRow(1).getPhysicalNumberOfCells());
            // 列表从0开始
            // System.out.println("first cols ="+sheet.getRow(1).getFirstCellNum());
            for (int i = sheet.getFirstRowNum() + 1; i < sheet.getLastRowNum(); i++) {
                row = sheet.getRow(i);
                System.out.println("row = " + row.getRowNum());
                
                /**
                 * 读取所有数据
                 */
                // for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++) {
                // row.getCell(j, Row.RETURN_NULL_AND_BLANK).setCellType(Cell.CELL_TYPE_STRING);
                // cell = row.getCell(j).getStringCellValue();
                // System.out.print(cell+"\t");
                // }
                
                Date beginDate = row.getCell(2).getDateCellValue();
                Date endDate = row.getCell(3).getDateCellValue();
                Date activityDate = row.getCell(4).getDateCellValue();
                    
                // 判断礼品卡是否有超额的或过期的情况,如果超额或者过期,这输出有问题的订单号
                if (row.getCell(6).getNumericCellValue() > row.getCell(7).getNumericCellValue() || beginDate.after(endDate) || null == activityDate)
                    System.out.println(row.getCell(0).getStringCellValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //检测代码
         try {
         // 读取excel2007
         readExcle2007();
         } catch (Exception ex) {
         }
         Long endTime = System.currentTimeMillis();

    }
}


以上程序依赖插件poi-3.8,大家可以从我的资源里无偿下载,代码拷过来就可以跑了。添加支持有:





原创粉丝点击