Excel读取(jxl)

package com.suning.crawler.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.log4j.Logger;

/**
* Excel读取,存放为List
*
* @author xxx
*/
public class ExcelRead
{
// 日志记录
private Logger logger = Logger.getLogger(ExcelRead.class);

/**
* 开始行
*/
private int beginRow;

/**
* 开始列
*/
private int beginColumn;

/**
* 结束行
*/
private int endRow;

/**
* 结束列
*/
private int endColumn;

public ExcelRead(int row, int column)
{
this(row, column, Integer.MAX_VALUE, Integer.MAX_VALUE);
}

public ExcelRead(int beginRow, int beginColumn, int endRow, int endColumn)
{
this.beginRow = beginRow;
this.beginColumn = beginColumn;
this.endRow = endRow;
this.endColumn = endColumn;
}

/**
* 读取Excel文件
*
* @param fileName
* 文件名称
* @return 文件信息
*/
public List<List<String>> readData(String fileName)
{
// 创建目录
String filePath = PropUtil.getProductPath();
// 创建文件
File file = new File(filePath + fileName);
return readData(file);
}

/**
* 读取Excel文件
*
* @param file
* Excel 文件
* @return 文件信息
*/
public List<List<String>> readData(File file)
{

// 打开文件
Workbook wb = null;
try
{
wb = Workbook.getWorkbook(file);
}
catch (BiffException e)
{
logger.error("jxl does not support the file format.", e);
return null;
}
catch (IOException e)
{
logger.error("read the file fails", e);
return null;
}
catch (Exception e)
{
logger.error("other exception", e);
return null;
}

// 存储sheet中的数据,第一个sheet
List<List<String>> datas = new ArrayList<List<String>>();
// 存储一行所有列数据数据
List<String> record = new ArrayList<String>();

// 读取第一个sheet的内容
Sheet sheet = wb.getSheet(0);
// 读取内容
for (int row = beginRow; row < endRow && row < sheet.getRows(); row++)
{
boolean validFlag = false;

for (int cloumn = beginColumn; cloumn < endColumn && cloumn < sheet.getColumns(); cloumn++)
{
String content = sheet.getCell(cloumn, row).getContents();
// 若一行为空,则标识为无效行
if (null != content && !"".equals(content.trim()))
{
validFlag = true;
}
record.add(content);
}
if (validFlag)
{
datas.add(record);
}
record.clear();
}
wb.close();

return datas;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值