POI-Excel表格使用流讀取和寫入

今天學習了Excel數據的寫入和讀取,這裏做下記錄

參考網址

POI – Excel參考文檔

POI介紹

POI是Apache軟件基金會用Java編寫的免費開源的跨平臺的 Java API,Apache POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。POI爲“Poor Obfuscation Implementation”的首字母縮寫,意爲“簡潔版的模糊實現”。
所以POI的主要功能是可以用Java操作Microsoft Office的相關文件,但是一般我們都是用來操作Excel相關文件。

使用前提

添加依賴

			<!--POI報表-->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.14</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>3.14</version>
            </dependency>

注意:

操作Excel文件區分版本:
2003版本(包含2003)以前的擴展名爲.xls需要用HSSFWorkbook類操作
2007版本(包含2007)以後的擴展名爲.xlsx需要用XSSFWorkbook類操作
這裏我是用的是2007版本

代碼實現

讀取文件數據

	/**
     * 使用POI讀取Excel文件數據
     */
    @Test
    public void read() throws IOException {
        //1.使用流讀取文件   --文件路徑自己更改
        FileInputStream inputStream =
                new FileInputStream(new File("C:\\Users\\hp\\Desktop\\aaaaa.xlsx"));
        //2.使用xssf創建workbook
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        //3.使用sheet-----根據索引
        XSSFSheet sheet = workbook.getSheetAt(0);
        //日期格式
        DataFormatter formatter = new DataFormatter();
        for (Row cells : sheet) {
            System.out.println(cells);
            for (Cell cell : cells) {
                /**
                 * 輸出字符串數據,如果有其他類型,運行會報錯,不會顯示其他格式的數據
                 * 要輸出其他格式,需選擇輸出的格式,如以下:
                 * getStringCellValue()   字符串數據
                 * getDateCellValue()     時間類型
                 */
//                System.out.println(cell.getStringCellValue());
                //轉換數據中含有日期的日期格式
                String text = formatter.formatCellValue(cell);
                System.out.println(text);
            }
        }
        workbook.close();
    }

效果圖

在這裏插入圖片描述

寫入文件數據

	/**
     * 寫入數據
     */
    @Test
    public void write() throws IOException {
        //創建Excel
        XSSFWorkbook workbook = new XSSFWorkbook();
        //2.創建sheet
        XSSFSheet sheet = workbook.createSheet("sheet0");
        //3.row cell-- 創建行表頭
        XSSFRow title = sheet.createRow(0);
        //創建cell單元格--表頭字段
        title.createCell(0).setCellValue("姓名");
        title.createCell(1).setCellValue("地址");
        title.createCell(2).setCellValue("年齡");
        //添加表數據
        XSSFRow dataRow = sheet.createRow(1);
        dataRow.createCell(0).setCellValue("張三");
        dataRow.createCell(1).setCellValue("河南省");
        dataRow.createCell(2).setCellValue("20");
		//寫入流  -- 文件路徑自己修改
        FileOutputStream outputStream =
                new FileOutputStream(new File("C:\\Users\\hp\\Desktop\\wwww.xlsx"));
        workbook.write(outputStream);
        outputStream.flush();
        workbook.close();
    }

效果圖

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章