使用poi只能判斷2003和2007進行資料讀取
阿新 • • 發佈:2019-01-09
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; 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.DateUtil; 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; /** * 操作Excel表格的功能類 可以判斷2003和2007兩個版本進行讀取 * @author LzwGLory * @version 建立時間:2014年7月21日 下午3:39:59 */ public class ExcelReader { private Workbook wb; private Sheet sheet; private Row row; /** * 讀取Excel表格表頭的內容 * @param InputStream * @return String 表頭內容的陣列 */ public String[] readExcelTitle(String path) { try { try {//用於判斷是2003還是2007 //2003 InputStream is = new FileInputStream(path); wb = new HSSFWorkbook(is); } catch (Exception e) { // TODO: handle exception //2007 InputStream is = new FileInputStream(path); wb = new XSSFWorkbook(is); } } catch (IOException e) { e.printStackTrace(); } sheet = wb.getSheetAt(0); row = sheet.getRow(0); // 標題總列數 int colNum = row.getPhysicalNumberOfCells(); System.out.println("colNum:" + colNum); String[] title = new String[colNum]; for (int i = 0; i < colNum; i++) { //title[i] = getStringCellValue(row.getCell((short) i)); title[i] = getCellFormatValue(row.getCell((short) i)); } return title; } /** * 讀取Excel資料內容 * @param InputStream * @return Map 包含單元格資料內容的Map物件 */ public Map<Integer, String> readExcelContent(String path) { Map<Integer, String> content = new HashMap<Integer, String>(); String str = ""; try { try {//用於判斷是2003還是2007 //2003 InputStream is = new FileInputStream(path); wb = new HSSFWorkbook(is); } catch (Exception e) { // TODO: handle exception //2007 InputStream is = new FileInputStream(path); wb = new XSSFWorkbook(is); } } catch (IOException e) { e.printStackTrace(); } sheet = wb.getSheetAt(0); // 得到總行數 int rowNum = sheet.getLastRowNum(); row = sheet.getRow(0); int colNum = row.getPhysicalNumberOfCells(); // 正文內容應該從第二行開始,第一行為表頭的標題 for (int i = 1; i <= rowNum; i++) { row = sheet.getRow(i); int j = 0; while (j < colNum) { // 每個單元格的資料內容用"-"分割開,以後需要時用String類的replace()方法還原資料 // 也可以將每個單元格的資料設定到一個javabean的屬性中,此時需要新建一個javabean // str += getStringCellValue(row.getCell((short) j)).trim() + // "-"; str += getCellFormatValue(row.getCell((short) j)).trim() + " "; j++; } content.put(i, str); str = ""; } return content; } /** * 讀取Excel資料內容1 * @param InputStream * @return Map 包含單元格資料內容的Map物件 */ public String[][] readExcelArrayContent(String path) { try { try {//用於判斷是2003還是2007 //2003 InputStream is = new FileInputStream(path); wb = new HSSFWorkbook(is); } catch (Exception e) { // TODO: handle exception //2007 InputStream is = new FileInputStream(path); wb = new XSSFWorkbook(is); } } catch (IOException e) { e.printStackTrace(); } sheet = wb.getSheetAt(0); // 得到總行數 int rowNum = sheet.getLastRowNum(); row = sheet.getRow(0); int colNum = row.getPhysicalNumberOfCells(); String[][] excelContentRoot=new String[rowNum][]; // 正文內容應該從第二行開始,第一行為表頭的標題 for (int i = 1; i <=rowNum; i++) { String[] excelContentChild=new String[colNum]; row = sheet.getRow(i); int j = 0; while (j < colNum) { excelContentChild[j]=getCellFormatValue(row.getCell((short) j)).trim(); j++; } excelContentRoot[i-1]=excelContentChild; } return excelContentRoot; } /** * 讀取Excel資料內容2 * @param InputStream * @return Map 包含單元格資料內容的Map物件 */ public List<String[]> readExcelListContent(String path) { List<String[]> lists=new ArrayList<String[]>(); try { try {//用於判斷是2003還是2007 //2003 InputStream is = new FileInputStream(path); wb = new HSSFWorkbook(is); } catch (Exception e) { // TODO: handle exception //2007 InputStream is = new FileInputStream(path); wb = new XSSFWorkbook(is); } } catch (IOException e) { e.printStackTrace(); } sheet = wb.getSheetAt(0); // 得到總行數 int rowNum = sheet.getLastRowNum(); row = sheet.getRow(0); int colNum = row.getPhysicalNumberOfCells(); String[][] excelContentRoot=new String[rowNum][]; // 正文內容應該從第二行開始,第一行為表頭的標題 for (int i = 1; i <=rowNum; i++) { String[] excelContentChild=new String[colNum]; row = sheet.getRow(i); int j = 0; while (j < colNum) { excelContentChild[j]=getCellFormatValue(row.getCell((short) j)).trim(); j++; } lists.add(excelContentChild); } return lists; } /** * 獲取單元格資料內容為字串型別的資料 * * @param cell Excel單元格 * @return String 單元格資料內容 */ private String getStringCellValue(Cell cell) { String strCell = ""; switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: strCell = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: strCell = String.valueOf(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: strCell = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_BLANK: strCell = ""; break; default: strCell = ""; break; } if (strCell.equals("") || strCell == null) { return ""; } if (cell == null) { return ""; } return strCell; } /** * 獲取單元格資料內容為日期型別的資料 * * @param cell * Excel單元格 * @return String 單元格資料內容 */ private String getDateCellValue(Cell cell) { String result = ""; try { int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_NUMERIC) { Date date = cell.getDateCellValue(); result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1) + "-" + date.getDate(); } else if (cellType == Cell.CELL_TYPE_STRING) { String date = getStringCellValue(cell); result = date.replaceAll("[年月]", "-").replace("日", "").trim(); } else if (cellType == Cell.CELL_TYPE_BLANK) { result = ""; } } catch (Exception e) { System.out.println("日期格式不正確!"); e.printStackTrace(); } return result; } /** * 根據Cell型別設定資料 * @param cell * @return */ private String getCellFormatValue(Cell cell) { String cellvalue = ""; if (cell != null) { // 判斷當前Cell的Type switch (cell.getCellType()) { // 如果當前Cell的Type為NUMERIC case Cell.CELL_TYPE_NUMERIC: case Cell.CELL_TYPE_FORMULA: { // 判斷當前的cell是否為Date if (DateUtil.isCellDateFormatted(cell)) { // 如果是Date型別則,轉化為Data格式 //方法1:這樣子的data格式是帶時分秒的:2011-10-12 0:00:00 //cellvalue = cell.getDateCellValue().toLocaleString(); //方法2:這樣子的data格式是不帶帶時分秒的:2011-10-12 Date date = cell.getDateCellValue(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); cellvalue = sdf.format(date); } // 如果是純數字 else { // 取得當前Cell的數值 cellvalue = String.valueOf(cell.getNumericCellValue()); } break; } // 如果當前Cell的Type為STRIN case Cell.CELL_TYPE_STRING: // 取得當前的Cell字串 cellvalue = cell.getRichStringCellValue().getString(); break; // 預設的Cell值 default: cellvalue = " "; } } else { cellvalue = ""; } return cellvalue; } public static void main(String[] args) { // // 對讀取Excel表格標題測試 // InputStream is = new FileInputStream("C:\\Users\\Administrator\\Desktop\\測試記錄.xls"); // ExcelReader excelReader = new ExcelReader(); // String[] title = excelReader.readExcelTitle(is); // System.out.println("獲得Excel表格的標題:"); // for (String s : title) { // System.out.print(s + " "); // } // // // 對讀取Excel表格內容測試 // InputStream is2 = new FileInputStream("C:\\Users\\Administrator\\Desktop\\測試記錄.xls"); // Map<Integer, String> map = excelReader.readExcelContent(is2); // System.out.println("獲得Excel表格的內容:"); // for (int i = 1; i <= map.size(); i++) { // System.out.println(map.get(i)); // } // // 對讀取Excel陣列內容測試 // InputStream is3 = new FileInputStream("C:\\Users\\Administrator\\Desktop\\測試記錄.xls"); // String[][] arrayContent = excelReader.readExcelArrayContent(is3); // System.out.println("獲得Excel陣列內容:"); // for (int i = 0; i < arrayContent.length; i++) { //// for(int j=0;j<arrayContent[i].length;j++){ //// if(arrayContent[i][j]==""||arrayContent[i][j]==null){ //// System.out.print("haha"+" "); //// }else{ //// System.out.print(arrayContent[i][j]+" "); //// } //// } //// System.out.println(); // System.out.println(Arrays.toString(arrayContent[i])); // } // 對讀取Excel表格標題測試 ExcelReader excelReader = new ExcelReader(); List<String[]> lists = excelReader.readExcelListContent("C:\\Users\\Administrator\\Desktop\\新匯入資料2.xlsx"); System.out.println("獲得Excel表格的標題:"); for(String[] arr:lists){ for(int i = 0; i < arr.length; i++){ if(arr[i].trim()==""){ System.out.print("haha"+" "+arr[i].trim().length()); }else{ System.out.print(arr[i].trim()+"長度:"+arr[i].trim().length()+" "); } } System.out.println(); } } }