java 讀取excel表


技術:apache.poi

maven依賴如下:

   <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

源代碼:

public static List getExcel() throws FileNotFoundException, IOException {
        File excelFile = new File("E:\\officeproject\\qysc\\test.xls");
        HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(excelFile));
        HSSFSheet sheet = wb.getSheetAt(0);
        List<List<String>> listAll = new ArrayList<List<String>>();
        for (Row row : sheet) {
            List<String> list = new ArrayList<String>();
            for (Cell cell : row) {
                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING://字符串
                        String  categoryName = cell.getRichStringCellValue().getString();
                        list.add(categoryName);
                        System.out.print(" ");
                        break;
                    case Cell.CELL_TYPE_NUMERIC://數值與日期
                        String axis = Double.toString(cell.getNumericCellValue());
                        list.add(axis);
                        System.out.print(" ");
                        break;
                    default:
                }
            }
            listAll.add(list);
            System.out.println();
        }
        System.out.println(listAll);
        System.out.println(listAll.size());
        return listAll;
    }

遇到的問題:

Exception in thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)

解決:關於excel不同版本讀取有對應的工具類,上述例子是對於后綴為 .xls 的excel表格。要是表格不多,就打開excel換一下后綴名就ok了

使用excel打開表格,文件- 另存為:

后綴選擇:

保存即可

 

補充2:關於手機的,在導入時,獲取了cell后,axis =Double.toString(cell.getNumericCellValue());這樣來讀取value時。例如手機號是:13111112222,讀取到的可能就是1.3111112222E10,解決措施:

參考:https://blog.csdn.net/maxu12345/article/details/47977811

DecimalFormat df = new DecimalFormat("#");
String axis = df.format(cell.getNumericCellValue());

 

補充3:關於百分數:2.5%

String axis = Double.toString(cell.getNumericCellValue());
NumberFormat nf = NumberFormat.getPercentInstance();
nf.setMaximumFractionDigits(1);//這個1的意識是保存結果到小數點后幾位,但是特別聲明:這個結果已經先*100了。
String telNum = df.format(cell.getNumericCellValue());

 

關於不同excel版本文件讀取,請參考:https://blog.csdn.net/it_wangxiangpan/article/details/42778167  (未測試,概不負責)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM