1 21 package org.dbunit.dataset.excel; 22 23 import org.apache.poi.hssf.usermodel.HSSFCell; 24 import org.apache.poi.hssf.usermodel.HSSFDateUtil; 25 import org.apache.poi.hssf.usermodel.HSSFRow; 26 import org.apache.poi.hssf.usermodel.HSSFSheet; 27 import org.dbunit.dataset.*; 28 import org.dbunit.dataset.datatype.DataType; 29 import org.dbunit.dataset.datatype.DataTypeException; 30 31 import java.math.BigDecimal ; 32 import java.util.ArrayList ; 33 import java.util.List ; 34 35 40 class XlsTable extends AbstractTable 41 { 42 private final ITableMetaData _metaData; 43 private final HSSFSheet _sheet; 44 45 public XlsTable(String sheetName, HSSFSheet sheet) throws DataSetException 46 { 47 int rowCount = sheet.getLastRowNum(); 48 if (rowCount > 0 && sheet.getRow(0) != null) 49 { 50 _metaData = createMetaData(sheetName, sheet.getRow(0)); 51 } 52 else 53 { 54 _metaData = new DefaultTableMetaData(sheetName, new Column[0]); 55 } 56 57 _sheet = sheet; 58 } 59 60 static ITableMetaData createMetaData(String tableName, HSSFRow sampleRow) 61 { 62 List columnList = new ArrayList (); 63 for (int i = 0; ; i++) 64 { 65 HSSFCell cell = sampleRow.getCell((short)i); 66 if (cell == null) 67 { 68 break; 69 } 70 71 Column column = new Column(cell.getStringCellValue(), 72 DataType.UNKNOWN); 73 columnList.add(column); 74 } 75 Column[] columns = (Column[])columnList.toArray(new Column[0]); 76 return new DefaultTableMetaData(tableName, columns); 77 } 78 79 82 public int getRowCount() 83 { 84 return _sheet.getLastRowNum(); 85 } 86 87 public ITableMetaData getTableMetaData() 88 { 89 return _metaData; 90 } 91 92 public Object getValue(int row, String column) throws DataSetException 93 { 94 assertValidRowIndex(row); 95 96 int columnIndex = getColumnIndex(column); 97 HSSFCell cell = _sheet.getRow(row + 1).getCell((short)columnIndex); 98 if (cell == null) 99 { 100 return null; 101 } 102 103 int type = cell.getCellType(); 104 switch (type) 105 { 106 case HSSFCell.CELL_TYPE_NUMERIC: 107 if (HSSFDateUtil.isCellDateFormatted(cell)) 108 { 109 return cell.getDateCellValue(); 110 } 111 return new BigDecimal (cell.getNumericCellValue()); 112 113 case HSSFCell.CELL_TYPE_STRING: 114 return cell.getStringCellValue(); 115 116 case HSSFCell.CELL_TYPE_FORMULA: 117 throw new DataTypeException("Formula not supported at row=" + 118 row + ", column=" + column); 119 120 case HSSFCell.CELL_TYPE_BLANK: 121 return null; 122 123 case HSSFCell.CELL_TYPE_BOOLEAN: 124 return cell.getBooleanCellValue() ? Boolean.TRUE : Boolean.FALSE; 125 126 case HSSFCell.CELL_TYPE_ERROR: 127 throw new DataTypeException("Error at row=" + row + 128 ", column=" + column); 129 130 default: 131 throw new DataTypeException("Unsupported type at row=" + row + 132 ", column=" + column); 133 } 134 } 135 } 136 137 | Popular Tags |