Apache?POI操作批量導(dǎo)入MySQL數(shù)據(jù)庫
poi介紹:
Apache POI是用Java編寫的免費(fèi)開源的跨平臺的Java API,Apache POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫的功能,其中使用最多的就是使用POI操作Excel文件。
POI使用到的相關(guān)maven依賴坐標(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 - 提供讀寫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ù)進(jìn)行讀取
/**
* 使用poi讀取表格數(shù)據(jù)
* @throws Exception
*/
@Test
public void test1() throws Exception {
// 1、加載指定的文件進(jìn)行讀取
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)報錯消息,后期通過代碼進(jìn)行判斷即可)
for (Cell cell : row) {
System.out.print(cell+" ");
}
System.out.println();
}
// 5、關(guān)閉讀取文件的流
excel.close();
}
輸出結(jié)果如下:
姓名 省份 城市
張三 廣東 高州
李四 四川 成都
POI操作Excel表格封裝了幾個核心對象:
XSSFWorkbook:工作簿
XSSFSheet:工作表
Row:行
Cell:單元格
1.2、從Excel文件讀取數(shù)據(jù)2
還有一種方式就是獲取工作表最后一個行號,從而根據(jù)行號獲得行對象,通過行獲取最后一個單元格索引,從而根據(jù)單元格索引獲取每行的一個單元格對象,代碼如下:
/**
* 使用poi讀取文件的第二種方式
* @throws Exception
*/
@Test
public void test2() throws Exception {
// 1、加載指定的文件進(jìn)行讀取
XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream("C:\\Users\\zhong\\Desktop\\poi.xlsx"));
// 2、讀取表格中的Sheet頁,通過索引決定
XSSFSheet sheetAt = excel.getSheetAt(0);
// 3、獲取當(dāng)前工作表中最后一個行號,注意行號是從0開啟的
int lastRowNum = sheetAt.getLastRowNum();
// 4、遍歷獲取到的行號
for (int i = 0; i <= lastRowNum; i++) {
// 5、根據(jù)行號獲取到每一行的數(shù)據(jù)
XSSFRow row = sheetAt.getRow(i);
// 6、獲取到當(dāng)前最后一個單元格索引
short lastCellNum = row.getLastCellNum();
// 7、遍歷當(dāng)前的單元格獲取到具體的數(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、關(guān)閉輸出
excel.close();
System.out.println("數(shù)據(jù)導(dǎo)出成功");
}
2、使用POI批量導(dǎo)入數(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 '約預(yù)日期',
number int null comment '可預(yù)約人數(shù)',
reservations int null comment '已預(yù)約人數(shù)'
)
charset = utf8;
批量導(dǎo)入預(yù)約設(shè)置信息操作過程:
1、點(diǎn)擊模板下載按鈕下載Excel模板文件
2、將預(yù)約設(shè)置信息錄入到模板文件中
3、點(diǎn)擊上傳文件按鈕將錄入完信息的模板文件上傳到服務(wù)器
4、通過POI讀取上傳文件的數(shù)據(jù)并保存到數(shù)據(jù)庫
創(chuàng)建對應(yīng)的實(shí)體類
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ù)格式
![[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-dbCEXvYt-1655542646539)(images/image-20220618142527340.png)]](http://img.jbzj.com/file_images/article/202206/2022062015113818.png)
修改頁面提供一個下載批量導(dǎo)入數(shù)據(jù)的模板按鈕
![[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-7OlfHCQJ-1655542646540)(images/image-20220618143241355.png)]](http://img.jbzj.com/file_images/article/202206/2022062015113819.png)
//下載模板文件
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、批量上傳文件的后端代碼編寫
關(guān)于上傳文件一般網(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++){
//獲得當(dāng)前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
//獲得當(dāng)前sheet的開始行
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)前行的開始列
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工作薄對象,表示整個excel
Workbook workbook = null;
try {
//獲取excel文件的io流
InputStream is = file.getInputStream();
//根據(jù)文件后綴名不同(xls和xlsx)獲得不同的Workbook實(shí)現(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;
}
//如果當(dāng)前單元格內(nè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來讀,避免出現(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遠(yuǎn)程調(diào)用了接口方法
/**
* 項(xià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、使用工具類解析上傳的數(shù)據(jù)
List<String[]> list = POIUtils.readExcel(excelFile);
// 將讀取的表格數(shù)據(jù)轉(zhuǎn)換為表格預(yù)約對象數(shù)據(jù)
List<OrderSetting> data = new ArrayList<>();
// 2、處理解析的數(shù)據(jù)
for (String[] strings : list) {
// 獲取到導(dǎo)入數(shù)據(jù)行的第一個單元格(預(yù)約時間)
String orderSate = strings[0];
// 獲取到導(dǎo)入數(shù)據(jù)行的第二個單元格(預(yù)約姓名)
String number = strings[1];
// 將重新獲取到的數(shù)據(jù)添加到預(yù)約集合中
OrderSetting orderSetting = new OrderSetting(new Date(orderSate), Integer.parseInt(number));
data.add(orderSetting);
}
// 2、通過dubbo遠(yuǎn)程調(diào)用服務(wù)實(shí)現(xiàn)數(shù)據(jù)批量導(dǎo)入到數(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)建批量上傳的接口實(shí)現(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;
/**
* 項(xiàng)目名稱:health_parent
* 描述:預(yù)約管理接口實(shí)現(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è)務(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ù)日期查詢預(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ù)訪問層接口和映射文件
package com.zcl.dao;
import com.itheima.pojo.OrderSetting;
import java.util.Date;
/**
* 項(xiàng)目名稱:health_parent
* 描述:預(yù)約管理數(shù)據(jù)訪問層
*
* @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);
/**
* 查詢預(yù)約數(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">
<!--添加預(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_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、批量導(dǎo)入數(shù)據(jù)測試
在上傳模板上制作數(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ù)庫的文章就介紹到這了,更多相關(guān)Apache POI操作批量導(dǎo)入MySQL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
linux下通過xinetd服務(wù)管理 rsync 實(shí)現(xiàn)開機(jī)自啟動
這篇文章主要介紹了linux下通過xinetd服務(wù)管理 rsync 實(shí)現(xiàn)開機(jī)自啟動的相關(guān)資料,需要的朋友可以參考下2017-10-10
Linux安裝Python虛擬環(huán)境virtualenv的方法
下面小編就為大家?guī)硪黄狶inux安裝Python虛擬環(huán)境virtualenv的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
CentOS 5.5使用yum來安裝LAMP(php運(yùn)行環(huán)境)
今天用yum方法搭建起了個LAMP環(huán)境,中間遇到了很多問題,經(jīng)過google和各位前輩的幫助,終于將環(huán)境搭建起來,現(xiàn)在把完整的步驟記錄下來,2010-09-09
VirtualBox下Centos6.8網(wǎng)絡(luò)配置教程
這篇文章主要為大家詳細(xì)介紹了VirtualBox下Centos6.8網(wǎng)絡(luò)配置教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
Centos Linux7設(shè)置靜態(tài)IP的實(shí)例
這篇文章主要介紹了Centos Linux7設(shè)置靜態(tài)IP的實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-05-05
服務(wù)器安裝寶塔面板無法遠(yuǎn)程連接數(shù)據(jù)庫的解決方法
這篇文章主要介紹了服務(wù)器安裝寶塔面板無法遠(yuǎn)程連接數(shù)據(jù)庫的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
銀河麒麟4.0.2(Ubuntu)擴(kuò)展boot分區(qū)過程介紹
大家好,本篇文章主要講的是銀河麒麟4.0.2(Ubuntu)擴(kuò)展boot分區(qū)過程介紹,感興趣的同學(xué)快來看一看吧,對你有幫助的話記得收藏一下哦2021-11-11
淺談Linux下通過find命令進(jìn)行rm文件刪除的小技巧
下面小編就為大家?guī)硪黄獪\談Linux下通過find命令進(jìn)行rm文件刪除的小技巧。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12

