Apache POI操作批量導(dǎo)入MySQL數(shù)據(jù)庫(kù)
目錄
- 1、POI操作入門(mén)案例
- 1.1、從Excel文件讀取數(shù)據(jù)1
- 1.2、從Excel文件讀取數(shù)據(jù)2
- 1.3、向Excel文件寫(xiě)入數(shù)據(jù)
- 2、使用POI批量導(dǎo)入數(shù)據(jù)到MySQL數(shù)據(jù)庫(kù)
- 2.1、創(chuàng)建導(dǎo)入數(shù)據(jù)的Excel模板文件
- 2.2、批量上傳文件的后端代碼編寫(xiě)
- 3、批量導(dǎo)入數(shù)據(jù)測(cè)試
poi介紹:
Apache POI是用Java編寫(xiě)的免費(fèi)開(kāi)源的跨平臺(tái)的Java API,Apache POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫(xiě)的功能,其中使用最多的就是使用POI操作Excel文件。
POI使用到的相關(guān)maven依賴(lài)坐標(biāo)如下:
<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的相關(guān)操作結(jié)果
HSSF - 提供讀寫(xiě)Microsoft Excel XLS格式檔案的功能XSSF - 提供讀寫(xiě)Microsoft Excel OOXML XLSX格式檔案的功能HWPF - 提供讀寫(xiě)Microsoft Word DOC格式檔案的功能HSLF - 提供讀寫(xiě)Microsoft PowerPoint格式檔案的功能HDGF - 提供讀Microsoft Visio格式檔案的功能HPBF - 提供讀Microsoft Publisher格式檔案的功能HSMF - 提供讀Microsoft Outlook格式檔案的功能
1、POI操作入門(mén)案例
1.1、從Excel文件讀取數(shù)據(jù)1
使用POI可以從一個(gè)已經(jīng)存在的Excel文件中讀取數(shù)據(jù)
前提需要建立一個(gè)需要讀取的表格數(shù)據(jù)進(jìn)行讀取
/** * 使用poi讀取表格數(shù)據(jù) * @throws Exception */@Testpublic void test1() throws Exception { // 1、加載指定的文件進(jìn)行讀取 XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream("C:\\Users\\zhong\\Desktop\\poi.xlsx")); // 2、讀取表格中的Sheet頁(yè),通過(guò)索引決定 XSSFSheet sheetAt = excel.getSheetAt(0); // 3、讀取Sheet頁(yè)中的行數(shù)據(jù) for (Row row : sheetAt) {// 4、讀取每一行數(shù)據(jù)的單元格數(shù)據(jù)(如果涉及到類(lèi)型裝轉(zhuǎn)換的可能出現(xiàn)報(bào)錯(cuò)消息,后期通過(guò)代碼進(jìn)行判斷即可)for (Cell cell : row) { System.out.print(cell+" ");}System.out.println(); } // 5、關(guān)閉讀取文件的流 excel.close();}
輸出結(jié)果如下:
姓名 省份 城市
張三 廣東 高州
李四 四川 成都
POI操作Excel表格封裝了幾個(gè)核心對(duì)象:
XSSFWorkbook:工作簿
XSSFSheet:工作表
Row:行
Cell:?jiǎn)卧?/p>
1.2、從Excel文件讀取數(shù)據(jù)2
還有一種方式就是獲取工作表最后一個(gè)行號(hào),從而根據(jù)行號(hào)獲得行對(duì)象,通過(guò)行獲取最后一個(gè)單元格索引,從而根據(jù)單元格索引獲取每行的一個(gè)單元格對(duì)象,代碼如下:
/** * 使用poi讀取文件的第二種方式 * @throws Exception */@Testpublic void test2() throws Exception { // 1、加載指定的文件進(jìn)行讀取 XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream("C:\\Users\\zhong\\Desktop\\poi.xlsx")); // 2、讀取表格中的Sheet頁(yè),通過(guò)索引決定 XSSFSheet sheetAt = excel.getSheetAt(0); // 3、獲取當(dāng)前工作表中最后一個(gè)行號(hào),注意行號(hào)是從0開(kāi)啟的 int lastRowNum = sheetAt.getLastRowNum(); // 4、遍歷獲取到的行號(hào) for (int i = 0; i <= lastRowNum; i++) {// 5、根據(jù)行號(hào)獲取到每一行的數(shù)據(jù)XSSFRow row = sheetAt.getRow(i);// 6、獲取到當(dāng)前最后一個(gè)單元格索引short lastCellNum = row.getLastCellNum();// 7、遍歷當(dāng)前的單元格獲取到具體的數(shù)據(jù)for (int j = 0; j < lastCellNum; j++) { // 獲取到單元格的對(duì)象 XSSFCell cell = row.getCell(j); // 輸出獲取到的數(shù)據(jù) System.out.print(cell + " ");}System.out.println(); } // 8、釋放資源 excel.close();}
1.3、向Excel文件寫(xiě)入數(shù)據(jù)
使用POI可以在內(nèi)存中創(chuàng)建一個(gè)Excel文件并將數(shù)據(jù)寫(xiě)入到這個(gè)文件,最后通過(guò)輸出流將內(nèi)存中的Excel文件下載到磁盤(pán)
/** * poi寫(xiě)出數(shù)據(jù)到磁盤(pán) */@Testpublic void test3() throws Exception { // 1、創(chuàng)建工作簿 XSSFWorkbook excel = new XSSFWorkbook(); // 2、創(chuàng)建工作簿中的表對(duì)象 XSSFSheet sheet = excel.createSheet("創(chuàng)建表"); // 3、創(chuàng)建第一行(表頭) XSSFRow row1 = sheet.createRow(0); // 4、在行中創(chuàng)建單元格數(shù)據(jù) row1.createCell(0).setCellValue("姓名"); row1.createCell(1).setCellValue("省份"); row1.createCell(2).setCellValue("城市"); row1.createCell(3).setCellValue("年齡"); // 5、創(chuàng)建第二行 XSSFRow row2 = sheet.createRow(1); // 6、創(chuàng)建第6行的數(shù)據(jù) row2.createCell(0).setCellValue("張三"); row2.createCell(1).setCellValue("遼寧"); row2.createCell(2).setCellValue("上海"); row2.createCell(3).setCellValue("50"); // 7、創(chuàng)建一個(gè)字節(jié)輸出流,將數(shù)據(jù)保存到本地 FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\zhong\\Desktop\\aaa.xlsx")); excel.write(fileOutputStream); fileOutputStream.flush(); // 8、關(guān)閉輸出 excel.close(); System.out.println("數(shù)據(jù)導(dǎo)出成功");}
2、使用POI批量導(dǎo)入數(shù)據(jù)到MySQL數(shù)據(jù)庫(kù)
創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)的表t_ordersetting
-- auto-generated definitioncreate table t_ordersetting( id int auto_incrementprimary key, orderDate date null comment "約預(yù)日期", number int null comment "可預(yù)約人數(shù)", reservations int null comment "已預(yù)約人數(shù)") charset = utf8;
批量導(dǎo)入預(yù)約設(shè)置信息操作過(guò)程:
1、點(diǎn)擊模板下載按鈕下載Excel模板文件
2、將預(yù)約設(shè)置信息錄入到模板文件中
3、點(diǎn)擊上傳文件按鈕將錄入完信息的模板文件上傳到服務(wù)器
4、通過(guò)POI讀取上傳文件的數(shù)據(jù)并保存到數(shù)據(jù)庫(kù)
創(chuàng)建對(duì)應(yīng)的實(shí)體類(lèi)
public class OrderSetting implements Serializable{ private Integer id ; private Date orderDate;//預(yù)約設(shè)置日期 private int number;//可預(yù)約人數(shù) private int reservations ;//已預(yù)約人數(shù) public OrderSetting() { } public OrderSetting(Date orderDate, int number) {this.orderDate = orderDate;this.number = number; }}
2.1、創(chuàng)建導(dǎo)入數(shù)據(jù)的Excel模板文件
目的是為了統(tǒng)一管理導(dǎo)入的數(shù)據(jù)格式
修改頁(yè)面提供一個(gè)下載批量導(dǎo)入數(shù)據(jù)的模板按鈕
//下載模板文件downloadTemplate(){ window.location.href="../../template/ordersetting_template.xlsx" rel="external nofollow" ;}
文件上傳前端代碼實(shí)現(xiàn)
<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>
提交函數(shù)
// 上傳之前進(jìn)行文件格式校驗(yàn)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、批量上傳文件的后端代碼編寫(xiě)
關(guān)于上傳文件一般網(wǎng)上都會(huì)有很多的工具類(lèi)可以下載使用,也就是別人將已經(jīng)封裝好的代碼拿出來(lái)分享給大家使用的
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工作薄對(duì)象Workbook workbook = getWorkBook(file);//創(chuàng)建返回對(duì)象,把每行中的值作為一個(gè)數(shù)組,所有行作為一個(gè)集合返回List<String[]> list = new ArrayList<String[]>();if(workbook != null){ for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){//獲得當(dāng)前sheet工作表Sheet sheet = workbook.getSheetAt(sheetNum);if(sheet == null){ continue;}//獲得當(dāng)前sheet的開(kāi)始行int firstRowNum = sheet.getFirstRowNum();//獲得當(dāng)前sheet的結(jié)束行int lastRowNum = sheet.getLastRowNum();//循環(huán)除了第一行的所有行for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){ //獲得當(dāng)前行 Row row = sheet.getRow(rowNum); if(row == null){continue; } //獲得當(dāng)前行的開(kāi)始列 int firstCellNum = row.getFirstCellNum(); //獲得當(dāng)前行的列數(shù) int lastCellNum = row.getPhysicalNumberOfCells(); String[] cells = new String[row.getPhysicalNumberOfCells()]; //循環(huán)當(dāng)前行 for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){Cell cell = row.getCell(cellNum);cells[cellNum] = getCellValue(cell); } list.add(cells);} } workbook.close();}return list; } //校驗(yàn)文件是否合法 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();//創(chuàng)建Workbook工作薄對(duì)象,表示整個(gè)excelWorkbook workbook = null;try { //獲取excel文件的io流 InputStream is = file.getInputStream(); //根據(jù)文件后綴名不同(xls和xlsx)獲得不同的Workbook實(shí)現(xiàn)類(lèi)對(duì)象 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;}//如果當(dāng)前單元格內(nèi)容為日期類(lèi)型,需要特殊處理String dataFormatString = cell.getCellStyle().getDataFormatString();if(dataFormatString.equals("m/d/yy")){ cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue()); return cellValue;}//把數(shù)字當(dāng)成String來(lái)讀,避免出現(xiàn)1讀成1.0的情況if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){ cell.setCellType(Cell.CELL_TYPE_STRING);}//判斷數(shù)據(jù)的類(lèi)型switch (cell.getCellType()){ case Cell.CELL_TYPE_NUMERIC: //數(shù)字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 = "未知類(lèi)型";break;}return cellValue; }}
2.2.1、創(chuàng)建批量上傳控制器
這里使用的dubbo遠(yuǎn)程調(diào)用了接口方法
/** * 項(xiàng)目名稱(chēng):health_parent * 描述:預(yù)約管理控制器 * * @author zhong * @date 2022-06-18 14:50 */@RestController@RequestMapping("/ordersetting")public class OrderSettingController { /** * 遠(yuǎn)程調(diào)用預(yù)約管理的服務(wù)接口 */ @Reference private OrderSettingService orderSettingService; /** * 文件上傳,實(shí)現(xiàn)預(yù)約管理的批量導(dǎo)入 * @param excelFile * @return */ @RequestMapping("/upload") public Result upload(@RequestParam("excelFile") MultipartFile excelFile){try { // 1、使用工具類(lèi)解析上傳的數(shù)據(jù) List<String[]> list = POIUtils.readExcel(excelFile); // 將讀取的表格數(shù)據(jù)轉(zhuǎn)換為表格預(yù)約對(duì)象數(shù)據(jù) List<OrderSetting> data = new ArrayList<>(); // 2、處理解析的數(shù)據(jù) for (String[] strings : list) {// 獲取到導(dǎo)入數(shù)據(jù)行的第一個(gè)單元格(預(yù)約時(shí)間)String orderSate = strings[0];// 獲取到導(dǎo)入數(shù)據(jù)行的第二個(gè)單元格(預(yù)約姓名)String number = strings[1];// 將重新獲取到的數(shù)據(jù)添加到預(yù)約集合中OrderSetting orderSetting = new OrderSetting(new Date(orderSate), Integer.parseInt(number));data.add(orderSetting); } // 2、通過(guò)dubbo遠(yuǎn)程調(diào)用服務(wù)實(shí)現(xiàn)數(shù)據(jù)批量導(dǎo)入到數(shù)據(jù)庫(kù) 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、創(chuàng)建批量上傳的接口實(shí)現(xiàn)類(lèi)
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;/** * 項(xiàng)目名稱(chēng):health_parent * 描述:預(yù)約管理接口實(shí)現(xiàn)類(lèi) * * @author zhong * @date 2022-06-18 15:09 */@Service(interfaceClass = OrderSettingService.class)@Transactionalpublic class OrderSettingImpl implements OrderSettingService { /** * 注入保存數(shù)據(jù) */ @Autowired private OrderSettingDao orderSettingDao; /** * 批量上傳業(yè)務(wù)實(shí)現(xiàn) * @param data */ @Override public void add(List<OrderSetting> data) {// 判斷集合數(shù)據(jù)是否為空if(data != null && data.size() > 0){ // 判斷當(dāng)前日期是否已經(jīng)進(jìn)行了預(yù)約設(shè)置 for (OrderSetting datum : data) {// 根據(jù)日期查詢(xún)預(yù)約消息long count = orderSettingDao.findCountByOrderDate(datum.getOrderDate());if(count > 0){ // 已進(jìn)行預(yù)約管理,執(zhí)行更新操作 orderSettingDao.editNumberByOrderDate(datum);}else{ // 添加預(yù)約設(shè)置 orderSettingDao.add(datum);} }}else{} }}
2.2.3、創(chuàng)建數(shù)據(jù)訪(fǎng)問(wèn)層接口和映射文件
package com.zcl.dao;import com.itheima.pojo.OrderSetting;import java.util.Date;/** * 項(xiàng)目名稱(chēng):health_parent * 描述:預(yù)約管理數(shù)據(jù)訪(fǎng)問(wèn)層 * * @author zhong * @date 2022-06-18 15:13 */public interface OrderSettingDao { /** * 添加預(yù)約數(shù)據(jù) * @param orderSetting */ void add(OrderSetting orderSetting); /** * 修改預(yù)約數(shù)據(jù) * @param orderSetting */ void editNumberByOrderDate(OrderSetting orderSetting); /** * 查詢(xún)預(yù)約數(shù)據(jù)的總數(shù) * @param orderDate * @return */ long findCountByOrderDate(Date orderDate);}
數(shù)據(jù)訪(fǎng)問(wèn)層映射文件編寫(xiě)SQL語(yǔ)句
<?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"> <!--添加預(yù)約嘻嘻嘻--> <insert id="add" parameterType="com.itheima.pojo.OrderSetting">insert into t_ordersetting (orderDate,number,reservations)values (#{orderDate},#{number},#{reservations}); </insert> <!--根據(jù)日期修改預(yù)約信息--> <update id="editNumberByOrderDate" parameterType="com.itheima.pojo.OrderSetting">update t_ordersettingset number = #{number}where orderDate = #{orderDate} </update> <!--根據(jù)日期查詢(xún)數(shù)據(jù)--> <select id="findCountByOrderDate" parameterType="date" resultType="java.lang.Long">select count(id)from t_ordersettingwhere orderDate = #{orderDate} </select></mapper>
3、批量導(dǎo)入數(shù)據(jù)測(cè)試
在上傳模板上制作數(shù)據(jù),然后進(jìn)行導(dǎo)入,先導(dǎo)入新的數(shù)據(jù)再導(dǎo)入修改后日期不變的數(shù)據(jù)再次上傳數(shù)據(jù)
到此這篇關(guān)于Apache POI操作批量導(dǎo)入MySQL數(shù)據(jù)庫(kù)的文章就介紹到這了,更多相關(guān)Apache POI操作批量導(dǎo)入MySQL內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
