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;
}
}
Excel读取(jxl)
猜你喜欢
转载自spacecity.iteye.com/blog/1465275
今日推荐
周排行