java調取XLS中的內容,已整合為UnitXlS類(最新版2018/10)
阿新 • • 發佈:2018-11-28
昨天開發遊戲的時候,需要xls表格進行獲取遊戲資料,存在txt檔案中存寫方式有點亂
像這張圖一樣,裝備資訊一覽無遺
這是一個UnitXLS,呼叫方法:AddXls(將xls中的資訊存入list) + 取內容(在list中取出)即可
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class UnitXLS implements GameConfig { // 陣列存放 // static List<Map<String, String>> list = null; public static void AddXls(List<Map<String, String>> list, String filePath, String[] queue) { // Excel文件 Workbook wb = null; // Excel文件中的一個sheet Sheet sheet = null; // 對應一個sheet中的一行 Row row = null; String cellData = null; // 將xls賦值到wb wb = readExcel(filePath); if (wb != null) { // 用來存放表中資料 // list = new ArrayList<Map<String, String>>(); // 獲取第一個sheet sheet = wb.getSheetAt(0); // 獲取最大行數 int rownum = sheet.getPhysicalNumberOfRows(); // 獲取第一行 row = sheet.getRow(0); // 獲取最大列數 int colnum = row.getPhysicalNumberOfCells(); for (int i = 1; i < rownum; i++) { Map<String, String> map = new LinkedHashMap<String, String>(); row = sheet.getRow(i); if (row != null) { for (int j = 0; j < colnum; j++) { cellData = (String) getCellFormatValue(row.getCell(j)); map.put(queue[j], cellData); } } else { break; } list.add(map); } } // 遍歷解析出來的list // for (Map<String,String> map : list) { // for (Entry<String,String> entry : map.entrySet()) { // System.out.print(entry.getKey()+":"+entry.getValue()+","); // } // System.out.println(); // } } /** * @param ID * * @return string型別的全部資訊 */ //ID為第幾行,僅僅使用這個方法,在使用這個方法前,要呼叫下AddXls初始化 public static String 取內容(List<Map<String, String>> list, int ID) { return String.valueOf(list.get(ID)); } // 讀取excel public static Workbook readExcel(String filePath) { Workbook wb = null; // 如果沒有該文件 if (filePath == null) { return null; } // 取檔案字尾名 String extString = filePath.substring(filePath.lastIndexOf(".")); InputStream is = null; try { is = new FileInputStream(filePath); if (".xls".equals(extString)) { return wb = new HSSFWorkbook(is); } else if (".xlsx".equals(extString)) { return wb = new XSSFWorkbook(is); } else { return wb = null; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return wb; } /** * 獲取單元格中的值並轉化成string * * @param cell * 單元格 * @return */ public static Object getCellFormatValue(Cell cell) { Object cellValue = null; if (cell != null) { // 判斷cell型別 switch (cell.getCellType()) { case NUMERIC: { cellValue = String.valueOf(cell.getNumericCellValue()); break; } case STRING: { cellValue = cell.getRichStringCellValue().getString(); break; } default: cellValue = ""; } } else { cellValue = ""; } return cellValue; } }