Apache POI操作批量導入MySQL數據庫
目錄
- 1、POI操作入門案例
- 1.1、從Excel文件讀取數據1
- 1.2、從Excel文件讀取數據2
- 1.3、向Excel文件寫入數據
- 2、使用POI批量導入數據到MySQL數據庫
- 2.1、創建導入數據的Excel模板文件
- 2.2、批量上傳文件的后端代碼編寫
- 3、批量導入數據測試
poi介紹:
Apache POI是用Java編寫的免費開源的跨平臺的Java API,Apache POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能,其中使用最多的就是使用POI操作Excel文件。
POI使用到的相關maven依賴坐標如下:
<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>
POI的相關操作結果
HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能HWPF - 提供讀寫Microsoft Word DOC格式檔案的功能HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能HDGF - 提供讀Microsoft Visio格式檔案的功能HPBF - 提供讀Microsoft Publisher格式檔案的功能HSMF - 提供讀Microsoft Outlook格式檔案的功能
1、POI操作入門案例
1.1、從Excel文件讀取數據1
使用POI可以從一個已經存在的Excel文件中讀取數據
前提需要建立一個需要讀取的表格數據進行讀取
/** * 使用poi讀取表格數據 * @throws Exception */@Testpublic void test1() throws Exception { // 1、加載指定的文件進行讀取 XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream("C:\\Users\\zhong\\Desktop\\poi.xlsx")); // 2、讀取表格中的Sheet頁,通過索引決定 XSSFSheet sheetAt = excel.getSheetAt(0); // 3、讀取Sheet頁中的行數據 for (Row row : sheetAt) {// 4、讀取每一行數據的單元格數據(如果涉及到類型裝轉換的可能出現報錯消息,后期通過代碼進行判斷即可)for (Cell cell : row) { System.out.print(cell+" ");}System.out.println(); } // 5、關閉讀取文件的流 excel.close();}
輸出結果如下:
姓名 省份 城市
張三 廣東 高州
李四 四川 成都
POI操作Excel表格封裝了幾個核心對象:
XSSFWorkbook:工作簿
XSSFSheet:工作表
Row:行
Cell:單元格
1.2、從Excel文件讀取數據2
還有一種方式就是獲取工作表最后一個行號,從而根據行號獲得行對象,通過行獲取最后一個單元格索引,從而根據單元格索引獲取每行的一個單元格對象,代碼如下:
/** * 使用poi讀取文件的第二種方式 * @throws Exception */@Testpublic void test2() throws Exception { // 1、加載指定的文件進行讀取 XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream("C:\\Users\\zhong\\Desktop\\poi.xlsx")); // 2、讀取表格中的Sheet頁,通過索引決定 XSSFSheet sheetAt = excel.getSheetAt(0); // 3、獲取當前工作表中最后一個行號,注意行號是從0開啟的 int lastRowNum = sheetAt.getLastRowNum(); // 4、遍歷獲取到的行號 for (int i = 0; i <= lastRowNum; i++) {// 5、根據行號獲取到每一行的數據XSSFRow row = sheetAt.getRow(i);// 6、獲取到當前最后一個單元格索引short lastCellNum = row.getLastCellNum();// 7、遍歷當前的單元格獲取到具體的數據for (int j = 0; j < lastCellNum; j++) { // 獲取到單元格的對象 XSSFCell cell = row.getCell(j); // 輸出獲取到的數據 System.out.print(cell + " ");}System.out.println(); } // 8、釋放資源 excel.close();}
1.3、向Excel文件寫入數據
使用POI可以在內存中創建一個Excel文件并將數據寫入到這個文件,最后通過輸出流將內存中的Excel文件下載到磁盤
/** * poi寫出數據到磁盤 */@Testpublic void test3() throws Exception { // 1、創建工作簿 XSSFWorkbook excel = new XSSFWorkbook(); // 2、創建工作簿中的表對象 XSSFSheet sheet = excel.createSheet("創建表"); // 3、創建第一行(表頭) XSSFRow row1 = sheet.createRow(0); // 4、在行中創建單元格數據 row1.createCell(0).setCellValue("姓名"); row1.createCell(1).setCellValue("省份"); row1.createCell(2).setCellValue("城市"); row1.createCell(3).setCellValue("年齡"); // 5、創建第二行 XSSFRow row2 = sheet.createRow(1); // 6、創建第6行的數據 row2.createCell(0).setCellValue("張三"); row2.createCell(1).setCellValue("遼寧"); row2.createCell(2).setCellValue("上海"); row2.createCell(3).setCellValue("50"); // 7、創建一個字節輸出流,將數據保存到本地 FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\zhong\\Desktop\\aaa.xlsx")); excel.write(fileOutputStream); fileOutputStream.flush(); // 8、關閉輸出 excel.close(); System.out.println("數據導出成功");}
2、使用POI批量導入數據到MySQL數據庫
創建一個數據庫的表t_ordersetting
-- auto-generated definitioncreate table t_ordersetting( id int auto_incrementprimary key, orderDate date null comment "約預日期", number int null comment "可預約人數", reservations int null comment "已預約人數") charset = utf8;
批量導入預約設置信息操作過程:
1、點擊模板下載按鈕下載Excel模板文件
2、將預約設置信息錄入到模板文件中
3、點擊上傳文件按鈕將錄入完信息的模板文件上傳到服務器
4、通過POI讀取上傳文件的數據并保存到數據庫
創建對應的實體類
public class OrderSetting implements Serializable{ private Integer id ; private Date orderDate;//預約設置日期 private int number;//可預約人數 private int reservations ;//已預約人數 public OrderSetting() { } public OrderSetting(Date orderDate, int number) {this.orderDate = orderDate;this.number = number; }}
2.1、創建導入數據的Excel模板文件
目的是為了統一管理導入的數據格式
修改頁面提供一個下載批量導入數據的模板按鈕
//下載模板文件downloadTemplate(){ window.location.href="../../template/ordersetting_template.xlsx" rel="external nofollow" ;}
文件上傳前端代碼實現
<el-upload action="/ordersetting/upload.do" name="excelFile" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload"> <el-button type="primary">上傳文件</el-button></el-upload>
提交函數
// 上傳之前進行文件格式校驗beforeUpload(file){ const isXLS = file.type === "application/vnd.ms-excel"; if(isXLS){return true; } const isXLSX = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; if (isXLSX) {return true; } this.$message.error("上傳文件只能是xls或者xlsx格式!"); return false;},// 上傳成功提示handleSuccess(response, file) { if(response.flag){this.$message({ message: response.message, type: "success"}); }else{this.$message.error(response.message); } console.log(response, file, fileList);},
2.2、批量上傳文件的后端代碼編寫
關于上傳文件一般網上都會有很多的工具類可以下載使用,也就是別人將已經封裝好的代碼拿出來分享給大家使用的
package com.zcl.utils;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;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;import org.springframework.web.multipart.MultipartFile;public class POIUtils { private final static String xls = "xls"; private final static String xlsx = "xlsx"; private final static String DATE_FORMAT = "yyyy/MM/dd"; /** * 讀入excel文件,解析后返回 * @param file * @throws IOException */ public static List<String[]> readExcel(MultipartFile file) throws IOException {//檢查文件checkFile(file);//獲得Workbook工作薄對象Workbook workbook = getWorkBook(file);//創建返回對象,把每行中的值作為一個數組,所有行作為一個集合返回List<String[]> list = new ArrayList<String[]>();if(workbook != null){ for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){//獲得當前sheet工作表Sheet sheet = workbook.getSheetAt(sheetNum);if(sheet == null){ continue;}//獲得當前sheet的開始行int firstRowNum = sheet.getFirstRowNum();//獲得當前sheet的結束行int lastRowNum = sheet.getLastRowNum();//循環除了第一行的所有行for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){ //獲得當前行 Row row = sheet.getRow(rowNum); if(row == null){continue; } //獲得當前行的開始列 int firstCellNum = row.getFirstCellNum(); //獲得當前行的列數 int lastCellNum = row.getPhysicalNumberOfCells(); String[] cells = new String[row.getPhysicalNumberOfCells()]; //循環當前行 for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){Cell cell = row.getCell(cellNum);cells[cellNum] = getCellValue(cell); } list.add(cells);} } workbook.close();}return list; } //校驗文件是否合法 public static void checkFile(MultipartFile file) throws IOException{//判斷文件是否存在if(null == file){ throw new FileNotFoundException("文件不存在!");}//獲得文件名String fileName = file.getOriginalFilename();//判斷文件是否是excel文件if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){ throw new IOException(fileName + "不是excel文件");} } public static Workbook getWorkBook(MultipartFile file) {//獲得文件名String fileName = file.getOriginalFilename();//創建Workbook工作薄對象,表示整個excelWorkbook workbook = null;try { //獲取excel文件的io流 InputStream is = file.getInputStream(); //根據文件后綴名不同(xls和xlsx)獲得不同的Workbook實現類對象 if(fileName.endsWith(xls)){//2003workbook = new HSSFWorkbook(is); }else if(fileName.endsWith(xlsx)){//2007workbook = new XSSFWorkbook(is); }} catch (IOException e) { e.printStackTrace();}return workbook; } public static String getCellValue(Cell cell){String cellValue = "";if(cell == null){ return cellValue;}//如果當前單元格內容為日期類型,需要特殊處理String dataFormatString = cell.getCellStyle().getDataFormatString();if(dataFormatString.equals("m/d/yy")){ cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue()); return cellValue;}//把數字當成String來讀,避免出現1讀成1.0的情況if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){ cell.setCellType(Cell.CELL_TYPE_STRING);}//判斷數據的類型switch (cell.getCellType()){ case Cell.CELL_TYPE_NUMERIC: //數字cellValue = String.valueOf(cell.getNumericCellValue());break; case Cell.CELL_TYPE_STRING: //字符串cellValue = String.valueOf(cell.getStringCellValue());break; case Cell.CELL_TYPE_BOOLEAN: //BooleancellValue = String.valueOf(cell.getBooleanCellValue());break; case Cell.CELL_TYPE_FORMULA: //公式cellValue = String.valueOf(cell.getCellFormula());break; case Cell.CELL_TYPE_BLANK: //空值cellValue = "";break; case Cell.CELL_TYPE_ERROR: //故障cellValue = "非法字符";break; default:cellValue = "未知類型";break;}return cellValue; }}
2.2.1、創建批量上傳控制器
這里使用的dubbo遠程調用了接口方法
/** * 項目名稱:health_parent * 描述:預約管理控制器 * * @author zhong * @date 2022-06-18 14:50 */@RestController@RequestMapping("/ordersetting")public class OrderSettingController { /** * 遠程調用預約管理的服務接口 */ @Reference private OrderSettingService orderSettingService; /** * 文件上傳,實現預約管理的批量導入 * @param excelFile * @return */ @RequestMapping("/upload") public Result upload(@RequestParam("excelFile") MultipartFile excelFile){try { // 1、使用工具類解析上傳的數據 List<String[]> list = POIUtils.readExcel(excelFile); // 將讀取的表格數據轉換為表格預約對象數據 List<OrderSetting> data = new ArrayList<>(); // 2、處理解析的數據 for (String[] strings : list) {// 獲取到導入數據行的第一個單元格(預約時間)String orderSate = strings[0];// 獲取到導入數據行的第二個單元格(預約姓名)String number = strings[1];// 將重新獲取到的數據添加到預約集合中OrderSetting orderSetting = new OrderSetting(new Date(orderSate), Integer.parseInt(number));data.add(orderSetting); } // 2、通過dubbo遠程調用服務實現數據批量導入到數據庫 orderSettingService.add(data);} catch (IOException e) { e.printStackTrace(); return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);}return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS); }}
2.2.2、創建批量上傳的接口實現類
package com.zcl.service.impl;import com.alibaba.dubbo.config.annotation.Service;import com.itheima.pojo.OrderSetting;import com.zcl.dao.OrderSettingDao;import com.zcl.service.OrderSettingService;import org.springframework.transaction.annotation.Transactional;import java.util.List;/** * 項目名稱:health_parent * 描述:預約管理接口實現類 * * @author zhong * @date 2022-06-18 15:09 */@Service(interfaceClass = OrderSettingService.class)@Transactionalpublic class OrderSettingImpl implements OrderSettingService { /** * 注入保存數據 */ @Autowired private OrderSettingDao orderSettingDao; /** * 批量上傳業務實現 * @param data */ @Override public void add(List<OrderSetting> data) {// 判斷集合數據是否為空if(data != null && data.size() > 0){ // 判斷當前日期是否已經進行了預約設置 for (OrderSetting datum : data) {// 根據日期查詢預約消息long count = orderSettingDao.findCountByOrderDate(datum.getOrderDate());if(count > 0){ // 已進行預約管理,執行更新操作 orderSettingDao.editNumberByOrderDate(datum);}else{ // 添加預約設置 orderSettingDao.add(datum);} }}else{} }}
2.2.3、創建數據訪問層接口和映射文件
package com.zcl.dao;import com.itheima.pojo.OrderSetting;import java.util.Date;/** * 項目名稱:health_parent * 描述:預約管理數據訪問層 * * @author zhong * @date 2022-06-18 15:13 */public interface OrderSettingDao { /** * 添加預約數據 * @param orderSetting */ void add(OrderSetting orderSetting); /** * 修改預約數據 * @param orderSetting */ void editNumberByOrderDate(OrderSetting orderSetting); /** * 查詢預約數據的總數 * @param orderDate * @return */ long findCountByOrderDate(Date orderDate);}
數據訪問層映射文件編寫SQL語句
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.zcl.dao.OrderSettingDao"> <!--添加預約嘻嘻嘻--> <insert id="add" parameterType="com.itheima.pojo.OrderSetting">insert into t_ordersetting (orderDate,number,reservations)values (#{orderDate},#{number},#{reservations}); </insert> <!--根據日期修改預約信息--> <update id="editNumberByOrderDate" parameterType="com.itheima.pojo.OrderSetting">update t_ordersettingset number = #{number}where orderDate = #{orderDate} </update> <!--根據日期查詢數據--> <select id="findCountByOrderDate" parameterType="date" resultType="java.lang.Long">select count(id)from t_ordersettingwhere orderDate = #{orderDate} </select></mapper>
3、批量導入數據測試
在上傳模板上制作數據,然后進行導入,先導入新的數據再導入修改后日期不變的數據再次上傳數據
到此這篇關于Apache POI操作批量導入MySQL數據庫的文章就介紹到這了,更多相關Apache POI操作批量導入MySQL內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!