您的位置:首页 > 编程语言 > Java开发

Java poi读取Excel表格

2015-11-16 19:56 513 查看
Java poi读取Excel表格,因为所用的是MongoDB数据库,用Document存储每行数据

上代码

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache. poi. hssf. usermodel. HSSFCell;
import org.apache. poi. hssf. usermodel. HSSFRow;
import org.apache. poi. hssf. usermodel. HSSFSheet;
import org.apache. poi. hssf. usermodel. HSSFWorkbook;
import org.apache. poi. poifs. filesystem. POIFSFileSystem;
import org.bson.Document;

/**
* 解析Excel表格
* 2015年11月14日 下午5:03:42
*/
public class ExcelRead {
private POIFSFileSystem fs;
private HSSFWorkbook wb;
private HSSFSheet sheet;
private HSSFRow row;

/**
*
* 2015年11月15日 上午11:55:48
*
* @param is
*            validate not null empty 可验证指定数据类型
* @return Map<String ,Object> status   ----  'success' or  'fail'
*                             message  ----  if success return Document,if fail  return error message
*/
public Map <String , Object> readExcelInsertMenu(InputStream is ) {
Map <String , Object> result = new HashMap< String, Object>();
try {
fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook( fs);
} catch (IOException e ) {
e. printStackTrace();
}
sheet = wb. getSheetAt( 0);
// 得到总行数
int rowNum = sheet. getLastRowNum();
// 得到第一行  根据第一列求出总列数colNum
row = sheet. getRow( 0);

List <Document > docs = new ArrayList< Document>();
int colNum = row. getPhysicalNumberOfCells();

// ----验证格式 不能为空 price必须为number类型 以及数据填充
for (int i = 1; i <= rowNum ; i++) {
row = sheet. getRow( i);
Document doc = new Document();
for (int j = 0; j < colNum ; j++) {
HSSFCell cell = row. getCell( j);
if (cell == null || cell.toString ().trim ().equals ("" )) {
result. put( "status", "fail");
result. put( "message", (i + 1) + " row " + (j + 1) + " cell  is empty.");
return result;
}
// ---price number 类型 类似类型也可如此判断
if (j == 3 ) {
if (cell .getCellType () != HSSFCell.CELL_TYPE_NUMERIC ) {
result. put( "status", "fail");
result. put( "message", (i + 1) + " row " + (j + 1) + " cell's format wrong" );
return result;
}
doc.put(sheet.getRow (0 ).getCell (j ).getStringCellValue (), cell.getNumericCellValue ());
continue;
}

doc.put(sheet.getRow (0 ).getCell (j ).getStringCellValue (), cell.getStringCellValue ());
}
docs. add( doc);
}
result. put( "status", "success");
result. put( "message", docs);
return result;
}

public static void main( String[] args ) {
try {
// 对读取Excel表格内容测试
InputStream is = new FileInputStream("d:\\menu.xls" );
ExcelRead excelMenu = new ExcelRead();
Map <String , Object> result = excelMenu.readExcelInsertMenu (is );
System. out.println (result );
} catch (FileNotFoundException e ) {
System. out.println ("未找到指定路径的文件!" );
e. printStackTrace();
}
}
}


可以根据实际需要设置返回类型,比如返回List,数据存储在Map
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: