本文主要是介绍Java poi读取Excel表格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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();// 得到第一行 根据第一列求出总列数colNumrow = 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
这篇关于Java poi读取Excel表格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!