国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel )

這篇具有很好參考價(jià)值的文章主要介紹了Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel )。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

?

目錄

Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)

代碼示例

導(dǎo)入Excel數(shù)據(jù)

將數(shù)據(jù)封裝好后傳給后端?

導(dǎo)出數(shù)據(jù)

預(yù)覽(vue-office/excel"……;docx-preview)

Excel 導(dǎo)入導(dǎo)出(后端處理:hutool+poi || Easy Excel )

前端

后端使用Hutool處理Excel 文件

Hutool-poi是針對(duì)Apache POI的封裝,因此需要用戶自行引入POI庫

導(dǎo)入

如何給導(dǎo)出的excel表頭設(shè)置中文?

?list里的對(duì)象有鍵值對(duì),鍵為表頭,值為表頭下的內(nèi)容


一、Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)

  1. 調(diào)用文件對(duì)象的 arrayBuffer 方法讀取文件,然后使用 xslx.read 方法解析數(shù)為 Excel 工作簿對(duì)象??
  2. readAsBinaryString readAsArrayBufferFileReader 對(duì)象的兩種不同讀取文件的方式:
  • 創(chuàng)建 FileReader 對(duì)象。使用FileReader 對(duì)象的讀取文件方法readAsBinaryString ,將文件讀取為二進(jìn)制字符串;或使用 readAsArrayBuffer 方法會(huì)將文件讀取為二進(jìn)制數(shù)據(jù)緩沖區(qū),即ArrayBuffer對(duì)象。
  • 再使用 xslx.read 方法解析數(shù)據(jù)為 Excel 工作簿對(duì)象? ??

? ?3.下圖為Excel 工作簿對(duì)象實(shí)例:

Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel ),狀態(tài)模式

Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel ),狀態(tài)模式

代碼示例
導(dǎo)入Excel數(shù)據(jù)
const reader = new FileReader()
reader.readAsBinaryString(file)
reader.onload = function (e) { 
    const data = e.target.result
    let wb = XLSX.read(data, {//Excel 工作簿對(duì)象,打印如上
        type: 'binary'
    })
}


const reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onload = function (e) {
    const data = e.target.result
    let wb = XLSX.read(data, {
        type: 'array'
    })
}
  1. 創(chuàng)建 FileReader 對(duì)象。
  2. 使用FileReader 對(duì)象的讀取文件方法readAsBinaryString ,將文件讀取為二進(jìn)制字符串。

(使用 readAsArrayBuffer 方法會(huì)將文件讀取為二進(jìn)制數(shù)據(jù)緩沖區(qū),即ArrayBuffer對(duì)象

  1. 設(shè)置 onload 回調(diào)函數(shù),該函數(shù)在文件讀取成功后觸發(fā)。
  2. 在回調(diào)函數(shù)中,通過 e.target.result 獲取讀取文件成功的結(jié)果值,即文件的二進(jìn)制數(shù)據(jù)。
  3. 使用 XLSX.read 方法解析二進(jìn)制字符串ArrayBuffer對(duì)象為 Excel 工作簿對(duì)象

type: 'binary' 表示解析的數(shù)據(jù)類型是二進(jìn)制字符串;type: 'array'表解析的數(shù)據(jù)類型是ArrayBuffer對(duì)象

  1. 如果提供了回調(diào)函數(shù) callback,則調(diào)用該函數(shù),并將解析得到的 workbook 對(duì)象傳遞給回調(diào)函數(shù)。

這個(gè)流程適用于在前端處理 Excel 文件,你可以在回調(diào)函數(shù)中進(jìn)一步處理 workbook 對(duì)象,比如獲取工作表、將工作表轉(zhuǎn)換為 JSON 等。

/*

readAsBinaryString readAsArrayBufferFileReader 對(duì)象的兩種不同讀取文件的方式。

readAsBinaryString 方法是過時(shí)的

官方推薦使用 readAsArrayBuffer 方法

*/

<input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">

let _file = e.target.files[0];//獲取input標(biāo)簽里的文件

_file.arrayBuffer().then((res) => {
    const wb = XLSX.read(res);
});

使用 arrayBuffer 方法,更符合現(xiàn)代 JavaScript 異步風(fēng)格

  1. 獲取input標(biāo)簽里的文件
  2. 調(diào)用文件對(duì)象的 arrayBuffer 方法,該方法返回一個(gè) Promise,該 Promise 在文件數(shù)據(jù)準(zhǔn)備好時(shí)解析。
  3. then 方法中,獲取解析后的二進(jìn)制數(shù)據(jù) res。
  4. 使用 XLSX.read 方法解析二進(jìn)制數(shù)據(jù),得到 wb,這里的 read 方法是你項(xiàng)目中封裝的讀取 Excel 數(shù)據(jù)的函數(shù)。
將數(shù)據(jù)封裝好后傳給后端?
// XLSX.utils.sheet_to_json
const sheet1 = wb.Sheets.Sheet1
const _data = utils.sheet_to_json(sheet1);

const wsname = wb.SheetNames[0]; //取Excel 工作簿對(duì)象的第一張表
const ws = XLSX.utils.sheet_to_json(wb.Sheets[wsname]); //將那張表轉(zhuǎn)成json表格內(nèi)容(實(shí)際上是數(shù)組)
//把解析出來的Excel數(shù)據(jù),直接轉(zhuǎn)成表格需要的數(shù)據(jù)
ws.forEach((item) => {
    that.lists.push({
        //處理后端要接收的數(shù)據(jù)格式
        // factoryName: item["工廠"],
        // wokhouseName: item["車間"],
    });
    console.log(that.lists);
})
  1. 取Excel 工作簿對(duì)象的第一張表
  2. 使用XLSX.utils.sheet_to_json將那張表轉(zhuǎn)成json表格內(nèi)容
  3. 可處理轉(zhuǎn)化的JSON數(shù)據(jù)為后端所需要的格式
導(dǎo)出數(shù)據(jù)
let book = XLSX.utils.book_new()
let aoa = [
  ['姓名', '性別', '年齡', '注冊(cè)時(shí)間'],
  ['張三', '男', 18, new Date()],
  ['李四', '女', 22, new Date()]
];
// 將一個(gè)二維數(shù)組轉(zhuǎn)成sheet
// aoa_to_sheet: 這個(gè)工具類最強(qiáng)大也最實(shí)用了,將一個(gè)二維數(shù)組轉(zhuǎn)成sheet,會(huì)自動(dòng)處理number、string、boolean、date等類型數(shù)據(jù);
let sheet = XLSX.utils.aoa_to_sheet(aoa);
XLSX.utils.book_append_sheet(book, sheet, "sheet1")
XLSX.writeFile(book, `user${new Date().getTime()}.xls`)
},


const wb = XLSX.utils.book_new(); 
let data = [
  { name: "張三", id: 100, score: 99 },
  { name: "張四", id: 200, score: 99 },
  { name: "張五", id: 300, score: 99 }
]//轉(zhuǎn)化JSON數(shù)組 
const ws = XLSX.utils.json_to_sheet(data); 
XLSX.utils.book_append_sheet(wb, ws, "people"); 
XLSX.writeFile(wb, "test1.xlsx");
  1. 使用XLSX.utils.aoa_to_sheet方法將一個(gè)二維數(shù)組轉(zhuǎn)化為一個(gè)工作表(sheet)。

一個(gè)包含對(duì)象的數(shù)組 data,通過 XLSX.utils.json_to_sheet 方法將其轉(zhuǎn)換為 Excel 工作表

  1. 使用XLSX.utils.book_new方法創(chuàng)建一個(gè)新的工作簿(book)。
  2. 使用XLSX.utils.book_append_sheet方法將之前創(chuàng)建的工作表添加到工作簿中,并命名為"sheet1"。
  3. 使用XLSX.writeFile方法將工作簿保存為一個(gè)Excel文件。

const reader = new FileReader()
reader.readAsBinaryString(file)
//onload 回調(diào)函數(shù),該函數(shù)在文件讀取成功后觸發(fā)
reader.onload = function (e) { 
    //回調(diào)函數(shù)中,通過 e.target.result 獲取讀取文件成功的結(jié)果值,即文件的二進(jìn)制數(shù)據(jù)BinaryString
    const data = e.target.result
    //使用 XLSX.read 方法解析二進(jìn)制數(shù)據(jù)BinaryString,type: 'binary為 Excel 工作簿對(duì)象
    let wb = XLSX.read(data, {
        type: 'binary'
    })
}

/* 
readAsBinaryString 和 readAsArrayBuffer 是 FileReader 對(duì)象的兩種不同讀取文件的方式。
readAsBinaryString 方法是過時(shí)的
官方推薦使用 readAsArrayBuffer 方法
*/
const reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onload = function (e) {
    const data = e.target.result
    let wb = XLSX.read(data, {//Excel 工作簿對(duì)象
        type: 'array'
    })
}
//————————————————————————————————————————————————————————

<input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">

//使用 arrayBuffer 方法,更符合現(xiàn)代 JavaScript 異步風(fēng)格
let _file = e.target.files[0];//獲取input標(biāo)簽里的文件
//調(diào)用文件對(duì)象的arrayBuffer方法,該方法返回一個(gè) Promise,該 Promise 在文件數(shù)據(jù)準(zhǔn)備好時(shí)解析
_file.arrayBuffer().then((res) => {
	//在 then 方法中,獲取解析后的二進(jìn)制數(shù)據(jù) res。
    const wb = read(res);
});

//————————————————————————————————————————————————————
// XLSX.utils.sheet_to_json
const sheet1 = wb.Sheets.Sheet1
const _data = utils.sheet_to_json(sheet1);

const wsname = wb.SheetNames[0]; //取Excel 工作簿對(duì)象的第一張表
const ws = XLSX.utils.sheet_to_json(wb.Sheets[wsname]); //將那張表轉(zhuǎn)成json表格內(nèi)容(實(shí)際上是 )
//把解析出來的Excel數(shù)據(jù),直接轉(zhuǎn)成表格需要的數(shù)據(jù)
ws.forEach((item) => {
    that.lists.push({
        //處理后端要接收的數(shù)據(jù)格式
        // factoryName: item["工廠"],
        // wokhouseName: item["車間"],
    });
    console.log(that.lists);
}) 
預(yù)覽(vue-office/excel"……;docx-preview)

Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel ),狀態(tài)模式

<vueofficeExcel v-if="excelSrc" :src="excelSrc" style="height:500px"></vueofficeExcel>
<input type="file" @change="change" />

import vueofficeExcel from "@vue-office/excel";
import vueofficedocx from "@vue-office/docx";
import vueofficedpdf from "@vue-office/pdf";

change(e) {
  let _file = e.target.files[0]
  const fr = new FileReader();
  fr.readAsDataURL(_file);
  fr.onload = (e) =>{
    this.excelSrc = e.target.result;
  }
let fr = new FileReader(); 
fr.readAsDataURL(file);
let self = this;
fr.onload = function () {
  self.imgbase64 = fr.result
}
<div ref="docxPreview"></div>

import { renderAsync } from "docx-preview"

let _file = e.target.files[0];
//blob, arrayBuffer
renderAsync(_file, this.$refs.docxPreview)

Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel ),狀態(tài)模式

二、Excel 導(dǎo)入導(dǎo)出(后端處理:hutool+poi || Easy Excel )

1、前端
  1. 導(dǎo)入:前端直接返回給后端文件對(duì)象
  2. 導(dǎo)出選中的或?qū)С鋈浚?strong>將選中的id記錄在ids數(shù)組里;根據(jù)ids數(shù)組長(zhǎng)度判斷是選中導(dǎo)出還是導(dǎo)出全部;

調(diào)用接口:

導(dǎo)出全部的可向后端傳入ids.join(',')//把數(shù)組轉(zhuǎn)成字符串

導(dǎo)出全部的傳入用戶名參數(shù)

handleImport(res, file, fileList) {
  if (res.code === '200') {
    this.$message.success("操作成功")
    this.load(1)
  } else {
    this.$message.error(res.msg)
  }
},
exportData() {   // 批量導(dǎo)出數(shù)據(jù)
  if (!this.ids.length) {   // 沒有選擇行的時(shí)候,全部導(dǎo)出  或者根據(jù)我的搜索條件導(dǎo)出
    window.open('http://localhost:9090/user/export?token=' + this.user.token + "&username="
        + this.username + "&name=" + this.name)
  } else {      // [1,2,3] => '1,2,3'//選中的導(dǎo)出
    let idStr = this.ids.join(',')//把數(shù)組轉(zhuǎn)成字符串
    window.open('http://localhost:9090/user/export?token=' + this.user.token + '&ids=' + idStr)
  }
},

2、后端使用Hutool處理Excel 文件
Hutool-poi是針對(duì)Apache POI的封裝,因此需要用戶自行引入POI庫
<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.3.7</version> 
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>5.2.3</version>
</dependency>
導(dǎo)入
@PostMapping("/import")
public Result importData(MultipartFile file) throws IOException {
    ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
    List<User> userList = reader.readAll(User.class);//讀取所有數(shù)據(jù)并轉(zhuǎn)成user類
    // 寫入數(shù)據(jù)到數(shù)據(jù)庫
    try {
        userService.saveBatch(userList);
    } catch (Exception e) {
        e.printStackTrace();
        return Result.error("數(shù)據(jù)批量導(dǎo)入錯(cuò)誤");
    }
    return Result.success();
}

ExcelUtil : Hutool-poi 模塊中的一個(gè)工具類,用于處理 Excel 文件的讀寫。

  1. 通過 ExcelUtil.getReader(file.getInputStream()) 獲取了一個(gè) ExcelReader 對(duì)象
  2. 使用 reader.readAll(User.class) 讀取了 Excel 中的所有數(shù)據(jù)并將其轉(zhuǎn)換為 User 類的對(duì)象列表。
  3. 最后將這些對(duì)象列表通過 userService.saveBatch(userList) 寫入到數(shù)據(jù)庫中。
@GetMapping("/export")
public void exportData(@RequestParam(required = false) String username,
                       @RequestParam(required = false) String name,
                       @RequestParam(required = false) String ids,//1,2,3,4
                       HttpServletResponse response) throws IOException {
    ExcelWriter writer = ExcelUtil.getWriter(true);
    List<User> list;
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();

    if (StrUtil.isNotBlank(ids)) {
        // 將逗號(hào)分隔的字符串轉(zhuǎn)換為整數(shù)列表:["1","2","3"]  =>[1,2,3]
        List<Integer> idsArr1 = Arrays.stream(ids.split(regex ",")).map(Integer::value0f).collect(Collectors.tolist());
        queryWrapper.in(column: "id", idsArr1);
    } else {
        // 第一種全部導(dǎo)出或者條件導(dǎo)出
        queryWrapper.like(StrUtil.isNotBlank(username), column: "username", username);
        queryWrapper.like(StrUtil.isNotBlank(name), column: "name", name);
    }

    list = userService.list(queryWrapper);

    // 將查詢到的用戶數(shù)據(jù)寫入 Excel
    writer.write(list, true);//告知那些key是頭,讓后把key一樣的value放在同一列
    // 設(shè)置瀏覽器響應(yīng)的格式
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用戶信息表", "UTF-8") + ".xlsx");

ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
out.close();
writer.close();
}

判斷前端是否有傳過來ids,有就將其轉(zhuǎn)成數(shù)組并queryWrapper查詢出,沒有就根據(jù)其他條件查詢出數(shù)據(jù)列表

  1. 創(chuàng)建 ExcelWriter 對(duì)象,參數(shù)為是否是 XLSX 格式
  2. 將查詢到的用戶數(shù)據(jù)寫入 Excel,并告知那些key是表頭,讓后把key一樣的value放在同一列
  3. 設(shè)置瀏覽器響應(yīng)的格式和文件名
  4. 通過 writer.flush(out, true) 將 Excel 數(shù)據(jù)輸出到瀏覽器。
  5. 最后關(guān)閉輸出流和 ExcelWriter 對(duì)象
如何給導(dǎo)出的excel表頭設(shè)置中文?

只需要在實(shí)體類的屬性上面加一個(gè)注解 @Alias("中文")

Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel ),狀態(tài)模式

?list里的對(duì)象有鍵值對(duì),鍵為表頭,值為表頭下的內(nèi)容

?查詢出來的list里是一條條user對(duì)象,所以有鍵值對(duì)

Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel ),狀態(tài)模式

Excel生成-ExcelWriter | Hutool

map數(shù)據(jù)的寫法?

Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel ),狀態(tài)模式文章來源地址http://www.zghlxwxcb.cn/news/detail-820540.html

@GetMapping("/export")
public void exportData(@RequestParam(required = false) String username,
                       @RequestParam(required = false) String name,
                       @RequestParam(required = false) String ids,//1,2,3,4
                       HttpServletResponse response) throws IOException {
    ExcelWriter writer = ExcelUtil.getWriter(true);
    List<User> list;
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();

    if (StrUtil.isNotBlank(ids)) {
        // 將逗號(hào)分隔的字符串轉(zhuǎn)換為整數(shù)列表:["1","2","3"]  =>[1,2,3]
        List<Integer> idsArr1 = Arrays.stream(ids.split(regex ",")).map(Integer::value0f).collect(Collectors.tolist());
        queryWrapper.in(column: "id", idsArr1);
    } else {
        // 第一種全部導(dǎo)出或者條件導(dǎo)出
        queryWrapper.like(StrUtil.isNotBlank(username), column: "username", username);
        queryWrapper.like(StrUtil.isNotBlank(name), column: "name", name);
    }

    list = userService.list(queryWrapper);

    // 將查詢到的用戶數(shù)據(jù)寫入 Excel
    writer.write(list, true);//告知那些key是頭,讓后把key一樣的value放在同一列
    // 設(shè)置瀏覽器響應(yīng)的格式
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用戶信息表", "UTF-8") + ".xlsx");

ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
out.close();
writer.close();
}


@PostMapping("/import")
public Result importData(MultipartFile file) throws IOException {
    ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
    List<User> userList = reader.readAll(User.class);//讀取所有數(shù)據(jù)并轉(zhuǎn)成user類
    // 寫入數(shù)據(jù)到數(shù)據(jù)庫
    try {
        userService.saveBatch(userList);
    } catch (Exception e) {
        e.printStackTrace();
        return Result.error("數(shù)據(jù)批量導(dǎo)入錯(cuò)誤");
    }
    return Result.success();
}

到了這里,關(guān)于Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel )的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包