Java利用poi讀取Excel詳解實現(xiàn)
前言
用戶可以直接讀取本地文件,也可以通過上傳文件的形式讀取excel
注意:poi對于讀取到空白行的時候,會默認的認為是最后一行,將不會再讀取空白行下面的數(shù)據(jù)
第一步導入依賴
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
第二步實現(xiàn)測試類+測試
- 創(chuàng)建ReloadExcelTest .java文件
- 此時找到excel的文件路徑,寫文件全名:路徑+文件全名
- 例:String reloadPath=“D:\ExcelTest\test.xlsx”;
- windows路徑之間加\\
- 測試
package tech.niua.admin.outputvalue.util.reloadexcel; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import tech.niua.admin.outputvalue.domain.OutputValue; import java.io.IOException; public class ReloadExcelTest { public static void readExcel(String reloadPath) throws IOException { //1.獲取工作簿 XSSFWorkbook workbook = new XSSFWorkbook(reloadPath); //2.獲取工作表 XSSFSheet sheet = workbook.getSheetAt(0); //獲取行 //cell.setCellType(Cell.CELL_TYPE_STRING); //將不同類型的數(shù)據(jù)類型轉為String int lastRowNum = sheet.getLastRowNum(); for (int i = 1; i <= lastRowNum; i++) { OutputValue outputValueEntity = OutputValue.builder().build(); Row rowValue = sheet.getRow(i); //獲取每一行中每一個單元格的數(shù)據(jù)的數(shù)據(jù) for (int j = 0; j < 4; j++) { DataFormatter formatter = new DataFormatter(); String value = formatter.formatCellValue(rowValue.getCell(j)); System.out.print(value+" "); } System.out.println(); } } }
注意:4.1.2版本的poi已經不在使用cell.setCellType(Cell.CELL_TYPE_STRING);這種對于讀取到數(shù)據(jù)設置為String類型的這種形式,將不再支持
改用為:
DataFormatter formatter = new DataFormatter();
String value = formatter.formatCellValue(rowValue.getCell(j));
此時value就是我們讀取到的值,可以做一個相應的轉換存儲到集合或者對象的形式接收
測試
public static void main(String[] args) throws IOException { String reloadPath="D:\\ExcelTest\\test.xlsx"; ReloadExcelTest.readExcel(reloadPath); }
實際應用
我們可以用集合的形式接收,或者以集合對象的形式接收,這樣就能夠對于讀取到的數(shù)據(jù)做一個操作處理,以便于后面實現(xiàn)批量上傳功能。
----->批量上傳:前端頁面上傳excel文件,由系統(tǒng)自動導入excel的數(shù)據(jù)到數(shù)據(jù)庫:
到此這篇關于Java利用poi讀取Excel詳解實現(xiàn)的文章就介紹到這了,更多相關Java讀取Excel內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Springboot項目使用html5的video標簽完成視頻播放功能
這篇文章主要介紹了Springboot項目使用html5的video標簽完成視頻播放功能,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12引入mybatis-plus報 Invalid bound statement錯誤問題的解決方法
這篇文章主要介紹了引入mybatis-plus報 Invalid bound statement錯誤問題的解決方法,需要的朋友可以參考下2020-05-05