Apache?POI操作批量導入MySQL數(shù)據(jù)庫
poi介紹:
Apache POI是用Java編寫的免費開源的跨平臺的Java API,Apache POI提供API給Java程序?qū)icrosoft 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文件讀取數(shù)據(jù)1
使用POI可以從一個已經(jīng)存在的Excel文件中讀取數(shù)據(jù)
前提需要建立一個需要讀取的表格數(shù)據(jù)進行讀取
/**
* 使用poi讀取表格數(shù)據(jù)
* @throws Exception
*/
@Test
public 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頁中的行數(shù)據(jù)
for (Row row : sheetAt) {
// 4、讀取每一行數(shù)據(jù)的單元格數(shù)據(jù)(如果涉及到類型裝轉(zhuǎn)換的可能出現(xiàn)報錯消息,后期通過代碼進行判斷即可)
for (Cell cell : row) {
System.out.print(cell+" ");
}
System.out.println();
}
// 5、關閉讀取文件的流
excel.close();
}
輸出結果如下:
姓名 省份 城市
張三 廣東 高州
李四 四川 成都
POI操作Excel表格封裝了幾個核心對象:
XSSFWorkbook:工作簿
XSSFSheet:工作表
Row:行
Cell:單元格
1.2、從Excel文件讀取數(shù)據(jù)2
還有一種方式就是獲取工作表最后一個行號,從而根據(jù)行號獲得行對象,通過行獲取最后一個單元格索引,從而根據(jù)單元格索引獲取每行的一個單元格對象,代碼如下:
/**
* 使用poi讀取文件的第二種方式
* @throws Exception
*/
@Test
public 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、根據(jù)行號獲取到每一行的數(shù)據(jù)
XSSFRow row = sheetAt.getRow(i);
// 6、獲取到當前最后一個單元格索引
short lastCellNum = row.getLastCellNum();
// 7、遍歷當前的單元格獲取到具體的數(shù)據(jù)
for (int j = 0; j < lastCellNum; j++) {
// 獲取到單元格的對象
XSSFCell cell = row.getCell(j);
// 輸出獲取到的數(shù)據(jù)
System.out.print(cell + " ");
}
System.out.println();
}
// 8、釋放資源
excel.close();
}
1.3、向Excel文件寫入數(shù)據(jù)
使用POI可以在內(nèi)存中創(chuàng)建一個Excel文件并將數(shù)據(jù)寫入到這個文件,最后通過輸出流將內(nèi)存中的Excel文件下載到磁盤
/**
* poi寫出數(shù)據(jù)到磁盤
*/
@Test
public void test3() throws Exception {
// 1、創(chuàng)建工作簿
XSSFWorkbook excel = new XSSFWorkbook();
// 2、創(chuàng)建工作簿中的表對象
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)建一個字節(jié)輸出流,將數(shù)據(jù)保存到本地
FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\zhong\\Desktop\\aaa.xlsx"));
excel.write(fileOutputStream);
fileOutputStream.flush();
// 8、關閉輸出
excel.close();
System.out.println("數(shù)據(jù)導出成功");
}
2、使用POI批量導入數(shù)據(jù)到MySQL數(shù)據(jù)庫
創(chuàng)建一個數(shù)據(jù)庫的表t_ordersetting
-- auto-generated definition
create table t_ordersetting
(
id int auto_increment
primary key,
orderDate date null comment '約預日期',
number int null comment '可預約人數(shù)',
reservations int null comment '已預約人數(shù)'
)
charset = utf8;
批量導入預約設置信息操作過程:
1、點擊模板下載按鈕下載Excel模板文件
2、將預約設置信息錄入到模板文件中
3、點擊上傳文件按鈕將錄入完信息的模板文件上傳到服務器
4、通過POI讀取上傳文件的數(shù)據(jù)并保存到數(shù)據(jù)庫
創(chuàng)建對應的實體類
public class OrderSetting implements Serializable{
private Integer id ;
private Date orderDate;//預約設置日期
private int number;//可預約人數(shù)
private int reservations ;//已預約人數(shù)
public OrderSetting() {
}
public OrderSetting(Date orderDate, int number) {
this.orderDate = orderDate;
this.number = number;
}
}
2.1、創(chuàng)建導入數(shù)據(jù)的Excel模板文件
目的是為了統(tǒng)一管理導入的數(shù)據(jù)格式

修改頁面提供一個下載批量導入數(shù)據(jù)的模板按鈕

//下載模板文件
downloadTemplate(){
window.location.href="../../template/ordersetting_template.xlsx" rel="external nofollow" ;
}
文件上傳前端代碼實現(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ù)
// 上傳之前進行文件格式校驗
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、批量上傳文件的后端代碼編寫
關于上傳文件一般網(wǎng)上都會有很多的工具類可以下載使用,也就是別人將已經(jīng)封裝好的代碼拿出來分享給大家使用的
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);
//創(chuàng)建返回對象,把每行中的值作為一個數(shù)組,所有行作為一個集合返回
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();
//循環(huán)除了第一行的所有行
for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
//獲得當前行
Row row = sheet.getRow(rowNum);
if(row == null){continue;
}
//獲得當前行的開始列
int firstCellNum = row.getFirstCellNum();
//獲得當前行的列數(shù)
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循環(huán)當前行
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();
//創(chuàng)建Workbook工作薄對象,表示整個excel
Workbook workbook = null;
try {
//獲取excel文件的io流
InputStream is = file.getInputStream();
//根據(jù)文件后綴名不同(xls和xlsx)獲得不同的Workbook實現(xiàn)類對象
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
//如果當前單元格內(nèi)容為日期類型,需要特殊處理
String dataFormatString = cell.getCellStyle().getDataFormatString();
if(dataFormatString.equals("m/d/yy")){
cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
return cellValue;
}
//把數(shù)字當成String來讀,避免出現(xiàn)1讀成1.0的情況
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判斷數(shù)據(jù)的類型
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: //Boolean
cellValue = 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、創(chuàng)建批量上傳控制器
這里使用的dubbo遠程調(diào)用了接口方法
/**
* 項目名稱:health_parent
* 描述:預約管理控制器
*
* @author zhong
* @date 2022-06-18 14:50
*/
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {
/**
* 遠程調(diào)用預約管理的服務接口
*/
@Reference
private OrderSettingService orderSettingService;
/**
* 文件上傳,實現(xiàn)預約管理的批量導入
* @param excelFile
* @return
*/
@RequestMapping("/upload")
public Result upload(@RequestParam("excelFile") MultipartFile excelFile){
try {
// 1、使用工具類解析上傳的數(shù)據(jù)
List<String[]> list = POIUtils.readExcel(excelFile);
// 將讀取的表格數(shù)據(jù)轉(zhuǎn)換為表格預約對象數(shù)據(jù)
List<OrderSetting> data = new ArrayList<>();
// 2、處理解析的數(shù)據(jù)
for (String[] strings : list) {
// 獲取到導入數(shù)據(jù)行的第一個單元格(預約時間)
String orderSate = strings[0];
// 獲取到導入數(shù)據(jù)行的第二個單元格(預約姓名)
String number = strings[1];
// 將重新獲取到的數(shù)據(jù)添加到預約集合中
OrderSetting orderSetting = new OrderSetting(new Date(orderSate), Integer.parseInt(number));
data.add(orderSetting);
}
// 2、通過dubbo遠程調(diào)用服務實現(xiàn)數(shù)據(jù)批量導入到數(shù)據(jù)庫
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)建批量上傳的接口實現(xiàn)類
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
* 描述:預約管理接口實現(xiàn)類
*
* @author zhong
* @date 2022-06-18 15:09
*/
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingImpl implements OrderSettingService {
/**
* 注入保存數(shù)據(jù)
*/
@Autowired
private OrderSettingDao orderSettingDao;
/**
* 批量上傳業(yè)務實現(xiàn)
* @param data
*/
@Override
public void add(List<OrderSetting> data) {
// 判斷集合數(shù)據(jù)是否為空
if(data != null && data.size() > 0){
// 判斷當前日期是否已經(jīng)進行了預約設置
for (OrderSetting datum : data) {
// 根據(jù)日期查詢預約消息
long count = orderSettingDao.findCountByOrderDate(datum.getOrderDate());
if(count > 0){
// 已進行預約管理,執(zhí)行更新操作
orderSettingDao.editNumberByOrderDate(datum);
}else{
// 添加預約設置
orderSettingDao.add(datum);
}
}
}else{
}
}
}
2.2.3、創(chuàng)建數(shù)據(jù)訪問層接口和映射文件
package com.zcl.dao;
import com.itheima.pojo.OrderSetting;
import java.util.Date;
/**
* 項目名稱:health_parent
* 描述:預約管理數(shù)據(jù)訪問層
*
* @author zhong
* @date 2022-06-18 15:13
*/
public interface OrderSettingDao {
/**
* 添加預約數(shù)據(jù)
* @param orderSetting
*/
void add(OrderSetting orderSetting);
/**
* 修改預約數(shù)據(jù)
* @param orderSetting
*/
void editNumberByOrderDate(OrderSetting orderSetting);
/**
* 查詢預約數(shù)據(jù)的總數(shù)
* @param orderDate
* @return
*/
long findCountByOrderDate(Date orderDate);
}
數(shù)據(jù)訪問層映射文件編寫SQL語句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//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>
<!--根據(jù)日期修改預約信息-->
<update id="editNumberByOrderDate" parameterType="com.itheima.pojo.OrderSetting">
update t_ordersetting
set number = #{number}
where orderDate = #{orderDate}
</update>
<!--根據(jù)日期查詢數(shù)據(jù)-->
<select id="findCountByOrderDate" parameterType="date" resultType="java.lang.Long">
select count(id)
from t_ordersetting
where orderDate = #{orderDate}
</select>
</mapper>
3、批量導入數(shù)據(jù)測試
在上傳模板上制作數(shù)據(jù),然后進行導入,先導入新的數(shù)據(jù)再導入修改后日期不變的數(shù)據(jù)再次上傳數(shù)據(jù)
到此這篇關于Apache POI操作批量導入MySQL數(shù)據(jù)庫的文章就介紹到這了,更多相關Apache POI操作批量導入MySQL內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持本站!
版權聲明:本站文章來源標注為YINGSOO的內(nèi)容版權均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。
關注官方微信