近日出于工作需要,总结了一下POI的HSSF操作Excel的用法,将之封装成一个类,便于以后重复使用。
封装主类:
查看代码 JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | package name.laigw.utils.excel; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; 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; /** * Handle excel(read and write) class by POI * * @author Gavin */ public class ExcelHandleByPOI { public static void main(String[] args) { String filePath = "input/test_from.xls"; String filePathTo = "input/test_to.xls"; List listList = ExcelHandleByPOI.readFromExcel(filePath, true); System.out.println("Data write to: " + ExcelHandleByPOI.writeToExcel(listList, filePathTo)); //~ display the table content for demo Iterator iterList = listList.iterator(); for(int h=0; iterList.hasNext(); ++h) { // get each 'list', indicating each table List listStr = (ArrayList)iterList.next(); Iterator iterStrArray = listStr.iterator(); System.out.println("Table[" + h + "]: "); System.out.print("\t"); int r = 0; for(; iterStrArray.hasNext(); ++r) { // get each String array, indicating each record of a table final String[] strArray = (String[])iterStrArray.next(); for(int i = 0; i < strArray.length; ++i) { if (i == 0) { System.out.print(strArray[i]); } else { System.out.print(", " + strArray[i]); } } System.out.println(); } } } /** * write data storing in list to excel corresponding to <i>filePath</i> * * @param list: structure: <i>list</i> has some sub list, * <br>each sub list corresponding to a sheet of excel. * <br>And each sub list has some String Array data, * <br>each String Array corresponding to a record of a sheet. * @param filePath * @return filePath */ public static String writeToExcel(final List list, String filePath) { FileOutputStream fileOut = null; // create a new work book HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = null; HSSFRow row = null; Iterator iterList = list.iterator(); for(int h=0; iterList.hasNext(); ++h) { // get each 'list', indicating each table sheet = wb.createSheet("Sheet " + (h+1)); List listStr = (ArrayList)iterList.next(); Iterator iterStrArray = listStr.iterator(); for(int r = 0; iterStrArray.hasNext(); ++r) { // get each String array, indicating each record of a table row = sheet.createRow(r); String[] strArr = (String[])iterStrArray.next(); for(int i=0; i < strArr.length; ++i) { row.createCell((short)i).setCellValue(strArr[i]); } } } try { SupportUtil.mkdir(SupportUtil.extractFileDir(filePath)); fileOut = new FileOutputStream(filePath); // write data to the new create file wb.write(fileOut); } catch (FileNotFoundException ex) { System.out.println("----------Error: " + ex); ex.printStackTrace(); } catch (IOException ex) { System.out.println("----------Error: " + ex); ex.printStackTrace(); } finally { try { //close the file fileOut.close(); } catch(IOException ex) { System.out.println("----------Error: " + ex); ex.printStackTrace(); } } return filePath; } /** * Read data into list from excel corresponding to filePath. * * @param filePath, absolute path(As "E:/input/abc.xls"), * <br>or relative path(As "input/abc.xls"), ralating to project root. * @param hasHead, tag for excel sheet format, indicating whether having table head. * @return List, storing data of the excel. * <br>list structure: * <br><i>list</i> has some sub list, * <br>each sub list corresponding to a sheet of excel. * <br>And each sub list has some String Array data, * <br>each String Array corresponding to a record of a sheet. */ public static List readFromExcel(String filePath, boolean hasHead) { List retList = new ArrayList(); FileInputStream filein = null; try { filein = new FileInputStream(filePath); // read data from file appointed by filePath POIFSFileSystem fs = new POIFSFileSystem(filein); // get POIFS file stream HSSFWorkbook wb = new HSSFWorkbook(fs); // workbook for(short h=0; h < wb.getNumberOfSheets(); ++h) { List list = new ArrayList(); final HSSFSheet sheet = wb.getSheetAt(h); int rowcount = sheet.getLastRowNum(); rowcount++; System.out.print("-----sheet[" + h + "]: row count = " + rowcount); int colcount = 0; for(int i=0; i < rowcount; ++i) { final HSSFRow row = sheet.getRow(i); // i=0 indicate the first row if (row == null) continue; // without the row, break and continue; if (colcount==0) { // colunm count set to column of the first effective row colcount = row.getLastCellNum(); System.out.println(", column count = " + colcount); } if (hasHead && i==0) { // if the sheet has "head", then ingore the head continue; } String[] fieldValue = new String[colcount]; for(short j=0; j < colcount; ++j) { // column data in the current final HSSFCell cell = row.getCell(j); fieldValue[j] = getCellStringValue(cell); } list.add(fieldValue); } retList.add(list); } } catch(Exception ex){ System.out.println("----------Error: " + ex.toString()); ex.printStackTrace(); } finally { try{ if(filein != null){ filein.close(); filein = null; } }catch(IOException ioe){ System.out.println("----------Error: " + ioe.toString()); } } return retList; } /** * get a <i>cell</i>'s value as String. * * @param cell * @return */ public static String getCellStringValue(HSSFCell cell) { String cellValue = ""; if(cell == null) return cellValue; switch(cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue().trim(); break; case HSSFCell.CELL_TYPE_NUMERIC: if ( HSSFDateUtil.isCellDateFormatted(cell) ) { cellValue = SupportUtil.datetimeFormat(cell.getDateCellValue()); } else if (SupportUtil.isInteger(cell.getNumericCellValue())) { cellValue = String.valueOf((int)cell.getNumericCellValue()); } else { cellValue = String.valueOf(cell.getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_FORMULA: cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cellValue = String.valueOf(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_ERROR: cellValue = String.valueOf(cell.getErrorCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_BLANK: default: cellValue = ""; } return cellValue; } } |
主类的辅助类:
查看代码 JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | package name.laigw.utils.excel; import java.io.File; import java.text.SimpleDateFormat; public class SupportUtil { /** * <b>set to world datetime(yyyy-MM-dd HH:mm:ss.SSS)</b> * @param date * @return */ public static String datetimeFormat(java.util.Date date) { SimpleDateFormat pdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); String dateStr = ""; try { if (date != null) { dateStr = pdf.format(date); } }catch (Exception e){ e.printStackTrace(); } return dateStr; } /** * extract file' directory, * <br>filepath="input/test_from.xls" * <br>return="input" * @param filepath * @return file directory */ public static String extractFileDir(String filepath) { return new File(filepath).getParent(); } /** * mkdir * @param pathname * @return:<br>true: mkdir successful; <br>false: mkdir fail */ public static boolean mkdir(String filedir) { return new File(filedir).mkdirs(); } /** * judge the input val whether can be a integer val without value changing. * <br>like 15.00 -> 15: true; 15.35 -> 15: false; * @param val * @return */ public static boolean isInteger(double val){ double exp = 0.0000000000000001; return (Math.abs(val - (int)val)) < exp; } } |