Java實現(xiàn)上傳Excel文件并導(dǎo)出到數(shù)據(jù)庫

前面有篇文章是從本地讀取Excel文件由桌,那樣做感覺太麻煩了捌斧,今天換了一種方法:上傳Excel文件并導(dǎo)出到數(shù)據(jù)庫丁存,多的不說觉增,上代碼
技術(shù)架構(gòu):SpringBoot+Mybatis
數(shù)據(jù)庫:Mysql

導(dǎo)入依賴

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>4.1.2</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml-schemas</artifactId>
  <version>4.1.2</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>4.1.2</version>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.16.20</version>
</dependency>

domain

實體類的字段根據(jù)自己Excel的表頭來決定,數(shù)據(jù)庫的表字段最好和實體類一一對應(yīng)

import lombok.Data;

// Excel實體類
@Data
public class Detailed {
  public Long id; // 主鍵
  public String auditDate; // 審核日期
  public Integer sceneId; // 場景id
  public String sceneName; // 場景名稱
  public String entityid; // entityid
  public Long housingResourcesId; // 房源id/實拍視頻id
  public Integer cityid; // cityid/城市id
  public String firstInstanceOA; // 初審oa/一審審核人oa
  public String firstInstance; // 初審方/一審核員部門名稱
  public String preliminaryResults; // 初審結(jié)果/一審審核結(jié)果
  public String reasonsForFirstInstance; // 初審原因/一審審核原因
  public String timeOfInitialExaminationAndStorage; // 初審入庫時間
  public String initialAuditTime; // 初審審核時間
  public Double shenheshichang; // shenheshichang
  public String timeoutStatus; // 超時狀態(tài)
  public String qualityInspectionResults; // 質(zhì)檢結(jié)果/質(zhì)檢審核結(jié)果
  public String qualityInspectionReasons; // 質(zhì)檢原因/質(zhì)檢審核原因
  public String qualificationStatus; // 質(zhì)檢合格原因
}

utils

獲取Excel表格中的數(shù)據(jù),其中// 獲取目標(biāo)單元格的值并存進對象中根據(jù)自己的實體類進行編寫

import com.iyunfish.tongcheng.domain.Detailed;
import org.apache.poi.ss.usermodel.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtils {
  public static List<Detailed> excelToShopIdList(InputStream inputStream) throws IOException {
    Workbook workbook = WorkbookFactory.create(inputStream);
    inputStream.close();
    // 在工作簿獲取目標(biāo)工作表
    Sheet sheet = workbook.getSheetAt(0);
    // 獲取到最后一行
    int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
    // 該集合用來儲存行對象
    ArrayList<Detailed> detaileds = new ArrayList<>();
    // 遍歷整張表鲸阔,從第二行開始赞警,第一行的表頭不要,循環(huán)次數(shù)不大于最后一行的值
    for (int i = 1; i < physicalNumberOfRows; i++) {
      // 該對象用來儲存行數(shù)據(jù)
      Detailed detailed = new Detailed();
      // 獲取當(dāng)前行數(shù)據(jù)
      Row row = sheet.getRow(i);
      // 獲取目標(biāo)單元格的值并存進對象中
      detailed.setAuditDate(row.getCell(0).getStringCellValue());
      detailed.setSceneId(Integer.valueOf(row.getCell(1).getStringCellValue()));
      detailed.setSceneName(row.getCell(2).getStringCellValue());
      detailed.setEntityid(row.getCell(3).getStringCellValue());
      detailed.setHousingResourcesId(Long.valueOf(row.getCell(4).getStringCellValue()));
      detailed.setCityid(Integer.valueOf(row.getCell(5).getStringCellValue()));
      detailed.setFirstInstanceOA(row.getCell(6).getStringCellValue());
      detailed.setFirstInstance(row.getCell(7).getStringCellValue());
      detailed.setPreliminaryResults(row.getCell(8).getStringCellValue());
      detailed.setReasonsForFirstInstance(row.getCell(9).getStringCellValue());
      detailed.setTimeOfInitialExaminationAndStorage(row.getCell(10).getStringCellValue());
      detailed.setInitialAuditTime(row.getCell(11).getStringCellValue());
      detailed.setShenheshichang(Double.valueOf(row.getCell(12).getStringCellValue()));
      detailed.setTimeoutStatus(row.getCell(13).getStringCellValue());
      detailed.setQualityInspectionResults(row.getCell(14).getStringCellValue());
      detailed.setQualityInspectionReasons(row.getCell(15).getStringCellValue());
      detailed.setQualificationStatus(row.getCell(16).getStringCellValue());
      // 把對象放到集合里
      detaileds.add(detailed);
      System.out.println("獲取到的當(dāng)前行數(shù)據(jù):" + detailed);
    }
    return detaileds;
  }
}

Controller

數(shù)據(jù)庫表的id點上自增秩彤,這樣添加的時候就不用再添加id了

import com.iyunfish.tongcheng.domain.Detailed;
import com.iyunfish.tongcheng.service.ReadService;
import com.iyunfish.tongcheng.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;

@Controller
public class UploadController {
  @Autowired
  private ReadService readService;

  @RequestMapping("/file/upload")
  public void pubggupload(@RequestParam("file") MultipartFile file) throws Exception {
    String name = file.getOriginalFilename();
    if(name.length() < 5 || !name.substring(name.length() - 5).equals(".xlsx")) {
      throw new Exception("文件格式錯誤");
    }
    // 獲取Excel中的數(shù)據(jù)
    List<Detailed> detaileds = ExcelUtils.excelToShopIdList(file.getInputStream());
    // 向數(shù)據(jù)庫遍歷添加數(shù)據(jù)庫
    for (int i = 0; i < detaileds.size(); i++) {
      // 獲取行信息
      Detailed detailed = detaileds.get(i);
      // 先根據(jù)eneityid查詢數(shù)據(jù)庫里有沒有一樣的,沒有就進行添加
      List<Long> longs = readService.queryDetailedByEneityid(detailed.getEntityid());
      if (longs.size() <= 0) {
        readService.addDetailed(detailed);
      } else {
        System.out.println("error:該條信息已存在 message:" + detailed);
      }
    }
  }
}

邏輯層接口和實現(xiàn)類沒有邏輯淤堵,直接到控制層的xml文件

xml

<?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.iyunfish.tongcheng.mapper.ReadMapper">
  <select id="queryDetailedByEneityid" parameterType="String" resultType="com.itZhao.domain.Detailed">
    SELECT
        id 
    FROM
        detailed 
    WHERE
        entityid = #{entityid}
  </select>

  <insert id="addDetailed" parameterType="com.iyunfish.tongcheng.domain.Detailed">
    INSERT INTO `tongcheng`.`detailed` (
      `audit_date`,
      `scene_id`,
      `scene_name`,
      `entityid`,
      `housing_resources_id`,
      `cityid`,
      `firstInstanceOA`,
      `firstInstance`,
      `preliminary_results`,
      `reasons_for_firstInstance`,
      `time_ofInitial_examination_and_storage`,
      `initial_audit_time`,
      `shenheshichang`,
      `timeout_status`,
      `quality_inspection_results`,
      `quality_inspection_reasons`,
      `qualification_status`
    )
    VALUES
    (#{read.auditDate}, #{read.sceneId}, #{read.sceneName}, #{read.entityid}, #{read.housingResourcesId}, #{read.cityid}, #{read.firstInstanceOA}, #{read.firstInstance}, #{read.preliminaryResults}, #{read.reasonsForFirstInstance}, #{read.timeOfInitialExaminationAndStorage}, #{read.initialAuditTime}, #{read.shenheshichang}, #{read.timeoutStatus}, #{read.qualityInspectionResults}, #{read.qualityInspectionReasons}, #{read.qualificationStatus})
    </insert>
</mapper>

到此代碼就寫完了贱勃,有不懂的或報錯解決不了的評論留言,看完啦點個

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市谷誓,隨后出現(xiàn)的幾起案子焕妙,更是在濱河造成了極大的恐慌研叫,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件窄坦,死亡現(xiàn)場離奇詭異凳寺,居然都是意外死亡彤侍,警方通過查閱死者的電腦和手機盏阶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來脑慧,“玉大人砰盐,你說我怎么就攤上這事岩梳。” “怎么了冀值?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵列疗,是天一觀的道長。 經(jīng)常有香客問我告材,道長竭讳,這世上最難降的妖魔是什么绢慢? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮胰舆,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘棘幸。我一直安慰自己倦零,他們只是感情好吨悍,可當(dāng)我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布育瓜。 她就那樣靜靜地躺著栽烂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪焰手。 梳的紋絲不亂的頭發(fā)上怀喉,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天磺送,我揣著相機與錄音灿意,去河邊找鬼缤剧。 笑死馅袁,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的荒辕。 我是一名探鬼主播汗销,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼抵窒!你這毒婦竟也來了弛针?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤李皇,失蹤者是張志新(化名)和其女友劉穎削茁,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體掉房,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡茧跋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年卓囚,在試婚紗的時候發(fā)現(xiàn)自己被綠了瘾杭。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡哪亿,死狀恐怖粥烁,靈堂內(nèi)的尸體忽然破棺而出贤笆,到底是詐尸還是另有隱情,我是刑警寧澤讨阻,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布苏潜,位于F島的核電站,受9級特大地震影響变勇,放射性物質(zhì)發(fā)生泄漏恤左。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一搀绣、第九天 我趴在偏房一處隱蔽的房頂上張望飞袋。 院中可真熱鬧,春花似錦链患、人聲如沸巧鸭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽纲仍。三九已至,卻和暖如春贸毕,著一層夾襖步出監(jiān)牢的瞬間郑叠,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工明棍, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留乡革,地道東北人。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓摊腋,卻偏偏與公主長得像沸版,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子兴蒸,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,573評論 2 359

推薦閱讀更多精彩內(nèi)容