1 16 package com.blandware.atleap.common.parsers.excel; 17 18 import com.blandware.atleap.common.Constants; 19 import com.blandware.atleap.common.parsers.SpecificPlainTextExtractor; 20 import com.blandware.atleap.common.parsers.exception.PlainTextExtractorException; 21 import org.apache.poi.hssf.usermodel.HSSFCell; 22 import org.apache.poi.hssf.usermodel.HSSFRow; 23 import org.apache.poi.hssf.usermodel.HSSFSheet; 24 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 25 import org.apache.poi.poifs.filesystem.POIFSFileSystem; 26 27 import java.io.IOException ; 28 import java.io.InputStream ; 29 import java.io.Writer ; 30 31 39 public class ExcelPlainTextExtractor implements SpecificPlainTextExtractor { 40 43 public ExcelPlainTextExtractor() { 44 } 45 46 56 public void extract(InputStream input, Writer output, String encoding) 57 throws PlainTextExtractorException { 58 try { 59 POIFSFileSystem fs = new POIFSFileSystem(input); 60 HSSFWorkbook workbook = new HSSFWorkbook(fs); 61 int numberOfSheets = workbook.getNumberOfSheets(); 62 63 for (int i = 0; i < numberOfSheets; i++) { 65 String sheetName = workbook.getSheetName(i); 67 if (sheetName != null) { 68 output.write(sheetName); 69 output.write(Constants.EOL); 70 } 71 HSSFSheet sheet = workbook.getSheetAt(i); 72 if (sheet != null) { 73 int firstRowNumber = sheet.getFirstRowNum(); 74 int lastRowNumber = sheet.getLastRowNum(); 75 for (int j = firstRowNumber; j <= lastRowNumber; j++) { 77 HSSFRow row = sheet.getRow(j); 78 if (row != null) { 79 short firstCellNumber = row.getFirstCellNum(); 80 short lastCellNumber = row.getLastCellNum(); 81 boolean cellIsPut = false; 84 for (short k = firstCellNumber; k <= lastCellNumber; k++) { 86 HSSFCell cell = row.getCell(k); 87 if (cell != null) { 88 int type = cell.getCellType(); 89 String value = null; 90 switch (type) { 91 case HSSFCell.CELL_TYPE_NUMERIC: 92 value = "" + cell.getNumericCellValue(); 93 break; 94 case HSSFCell.CELL_TYPE_STRING: 95 value = cell.getStringCellValue(); 96 break; 97 case HSSFCell.CELL_TYPE_FORMULA: 98 value = "" + cell.getNumericCellValue(); 99 break; 100 case HSSFCell.CELL_TYPE_BLANK: 101 value = ""; 102 break; 103 case HSSFCell.CELL_TYPE_BOOLEAN: 104 value = cell.getBooleanCellValue() 105 ? "true" : "false"; 106 break; 107 case HSSFCell.CELL_TYPE_ERROR: 108 value = ""; 109 break; 110 default: 111 value = ""; 112 break; 113 } 114 if (cellIsPut) { 115 output.write(' '); 116 } else { 117 cellIsPut = true; 118 } 119 output.write(value); 120 } 121 } output.write(Constants.EOL); 123 } 124 } } 126 } } catch (IOException e) { 128 throw new PlainTextExtractorException(e); 129 } 130 } 131 132 135 public String getUsedEncoding() { 136 return null; 137 } 138 } 139 | Popular Tags |