java ---讀取檔案
阿新 • • 發佈:2020-09-22
概要:讀取檔案的內容,並放入Map中。
程式碼:
'''
import java.io.FileInputStream; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Map; import java.util.HashMap; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; 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 fileinput{ public static void main(String [] args) { System.out.println("start"); getInputData("book1.xlsx"); System.out.println(inputdata.get("max"));//列印整行內容 System.out.println(inputdata.get("max").get(0));//列印單元格的內容 } public static Map<String,List<Double>> inputdata = new HashMap<String, List<Double>>();//inputdata用來儲存input.xlsx常量,key是String型別,取出 //的資料存放在List //獲取input.xlsx常量 public static void getInputData (String fileName) {//getInputdata靜態方法 File inputFile = new File(fileName);//inputfile物件 XSSFWorkbook wb = null;//初始化wb try { wb = new XSSFWorkbook(new FileInputStream(inputFile)); } catch (IOException e) { e.printStackTrace(); } int numberOfSheets = wb.getNumberOfSheets();//獲取sheet數 for (int x = 0; x < numberOfSheets; x++) {//迴圈sheet XSSFSheet sheet = wb.getSheetAt(x);//物件 for(int rowNum=0; rowNum<=sheet.getLastRowNum();rowNum++){//迴圈行數 XSSFRow xssfRow = sheet.getRow(rowNum); //物件 if (null != xssfRow) { String[] singleRow = new String[sheet.getLastRowNum()];//儲存每一行資料 int n = 0; for(int cosNum=0;cosNum<xssfRow.getLastCellNum();cosNum++){ //迴圈一行中所有單元格 XSSFCell cell = xssfRow.getCell(cosNum);//獲取單元格的內容 switch (cell.getCellType()) {//判斷單元格資料型別 case Cell.CELL_TYPE_NUMERIC: if (!DateUtil.isCellDateFormatted(cell)) {//不是日期型別時 cell.setCellType(Cell.CELL_TYPE_STRING);//設定單元格的資料型別為字串型別 String temp = cell.getStringCellValue();//讀取單元格的資料 if ( inputdata.get(singleRow[0]) != null){//讀取到的第一行不為空時 inputdata.get(singleRow[0]).add(new Double(temp));//資料加到第一行 } else {//為空時,將讀取的資料放入LIST中,將LIST加入inputdata 的第一行 List<Double> db = new ArrayList<Double>(); db.add(new Double(temp)); inputdata.put(singleRow[0], db); } } break; case Cell.CELL_TYPE_STRING: singleRow[n] = cell.getStringCellValue().trim(); break; } n++; } } } } }
}
相關的jar包:
自行下載,並放入工程檔案架下lib中。