java、springboot 接口導出txt方式

java、springboot 接口導出txt

就寫兩個方法

@Log
    @ApiOperation(value = "導出單碼/箱碼",produces = "application/octet-stream")
    @GetMapping(value = "/export")
    public void exportExcel(TraceBatchPageQuery page HttpServletResponse response){
        Page<TraceBatchDto> pages = traceBatchService.pageByParam(page);
        if (page.getRecords().size()==0)
            throw new BusinessException("數據為空");
      
        for(TraceBatchDto dto:pages.getRecords()){
            if (type==0)
                text.append(dto.getQuantity());
            else
                text.append(dto.getPackQuantity());
            text.append("\r\n");//換行字符
        }
        //導出的文件存儲目錄
        ExportUtil.exportTxt(response,text.toString());
    }
  /* 導出txt文件
     * @author
     * @param	response
     * @param	text 導出的字符串
     * @return
     */
    public static void exportTxt(HttpServletResponse response, String text,String name){
        response.setCharacterEncoding("utf-8");
        //設置響應的內容類型
        response.setContentType("text/plain");
        //設置文件的名稱和格式
        response.addHeader("Content-Disposition","attachment;filename="
                + "data.txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(text.getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            //LOGGER.error("導出文件文件出錯:{}",e);
        } finally {try {
            buff.close();
            outStr.close();
        } catch (Exception e) {
            //LOGGER.error("關閉流對象出錯 e:{}",e);
        }
        }
    }

Springboot 文件處理導入導出

簡單記錄下使用Springboot進行文件與後端交互、excel前臺導出等內容

這裡用到瞭:elelemt-ui\HTML\vue\Springboot框架

後臺導入

HTML:

        <el-button-group>
            <el-button @click="importExcel()" size="small" type = "primary">導入</el-button>
            <el-button @click="exportExcel()" size="small">導出</el-button>
        </el-button-group>

Javascript:響應importExcel彈窗,文件選擇,遍歷發送給後端

            importExcel: function () {
                this.upload();
                this.handleFile();
            },
            upload: function () {
                var inputObj = document.createElement('input');
                inputObj.setAttribute('id', 'file');
                inputObj.setAttribute('type', 'file');
                inputObj.setAttribute('name', 'file');
                inputObj.setAttribute("style", 'visibility:hidden');
                document.body.appendChild(inputObj);
                inputObj.value;
                inputObj.click();
                console.log(inputObj);
            },
            //處理文件
            handleFile: function () {
                document.querySelector('#file').addEventListener('change', function (e) {
                    for (let entry of e.target.files) {
                        //處理files
                        var fd = new FormData();
                        fd.append('file', entry);
                        fd.append('type', dotType+'dot_Detail');
                        fd.append('params', JSON.stringify({master_id:dotId,type:dotType}));
                        $.ajax({
                            url: "url", //請求的url地址
                            dataType: "json", //返回格式為json
                            async: false,//請求是否異步,默認為異步,這也是ajax重要特性
                            data: fd, //參數值
                            type: "POST", //請求方式
                            contentType: false,// 不設置Content-Type請求頭
                            processData: false,// 不處理發送的數據
                            success: function (res) { 
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) { 
                            }
                        });
                    }
                })
            },

Java:接收前端FormData()中包含的file\type\params字段,利用file在業務中使用POI或者Easy這樣的做導入功能開發

    @Autowired
    ExcelServiceImpl excelService;
 
    @RequestMapping("/read")
    @ResponseBody
    public ResposeObject read(@RequestParam MultipartFile file, String type, String params) {
        Map<String,Object> paramMap = JSONObject.parseObject(params,Map.class);
        try {
            if (file != null) {
                InputStream ins = file.getInputStream();
                excelService.read(ins,type,paramMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResposeHelper.ok("ok");
    }

前臺導入

HTML:

            <a v-on:click="importExcel()" href="javascript:void(0);" rel="external nofollow"  rel="external nofollow"  >
                從excel導入...
            </a>

Javascript:

data: function () {
            return {
                dataList: [
                    {
                        addr: '',
                        code: '',
                        start: '',
                        length: '',
                        crc: '',
                        rate: '',
                        state: ''
                    }
                ],
    }
}
mothods:{ 
            importExcel: function () {
                this.upload();
                this.handleFile();
            },
 
            upload: function () {
                var inputObj = document.createElement('input');
                inputObj.setAttribute('id', 'file');
                inputObj.setAttribute('type', 'file');
                inputObj.setAttribute('name', 'file');
                inputObj.setAttribute("style", 'visibility:hidden');
                document.body.appendChild(inputObj);
                inputObj.value;
                inputObj.click();
                console.log(inputObj);
                inputObj.value = '';
            },
            //處理文件
            handleFile: function () {
                document.querySelector('#file').addEventListener('change', function (e) {
                    for(let entry of e.target.files){
                        readFile(entry);
                    }
                })
            },
}
 
<script type="text/javascript">
   //循環讀取文件觸發parseXlsxObject方法操作業務
   function readFile(file) {
        var name = file.name;
        var reader = new FileReader();
        reader.onload = function (e) {
            var data = e.target.result;
            var wb = XLSX.read(data, {type: "binary"});
            parseXlsxObject(wb);
        };
        reader.readAsBinaryString(file);
    }
//實現導入到前端的List變量
function parseXlsxObject(wb) {
        var sheet = wb.Sheets.Sheet1;
        var json = XLSX.utils.sheet_to_json(sheet);
        json.forEach(function (value) {
            var item = {
                addr: value['地址位'],
                code: value['模式'],
                start: value['起始地址'],
                length: value['長度'],
                crc: value['crc校檢'],
                rate: value['頻率'],
                state: value['啟用狀態']
            }
            this.dataList.push(item);
        });
 
        /* 讀取方式有很多種,這裡推薦用xls.js上面官方的sheet_to_json方法
        console.log(json)
        var obj = {
            addr: '',
            code: '',
            start: '',
            length: '',
            crc: '',
            rate: '',
            state: ''
        };
        for (var i = 2; ; i < i++) {
            var row = "";
            eval("row = sheet.A" + i);
            if (row == null || row == undefined) {
                break;
            }
            var command = JSON.parse(JSON.stringify(obj));
            eval("command.addr=sheet.A" + i + ".w");
            eval("command.code=sheet.B" + i + ".w");
            eval("command.start=sheet.C" + i + ".w");
            eval("command.length=sheet.D" + i + ".w");
            eval("command.crc=sheet.E" + i + ".w");
            eval("command.rate=sheet.F" + i + ".w");
            eval("command.state=sheet.G" + i + ".w");
        }
        console.log(this.dataList);
        */
    }
</script>

前臺導出

HTML: 

            <a v-on:click="exportExcel()" href="javascript:void(0);" rel="external nofollow"  rel="external nofollow"  >
                導出到excel...
            </a>

Javascript:響應導出按鈕,將list通過xls的方法aoa_to_sheet導出為excel文檔

exportExcel: function () {
    var settingsArray = [['地址位','模式','起始地址','長度','crc校檢','頻率','啟用狀態']];
    this.dataList.forEach(function (row) {
    var settingArr = [row.addr,row.code,row.start,row.length,row.crc,row.rate,row.state];
            settingsArray.push(settingArr);
        });
        var sheet = XLSX.utils.aoa_to_sheet(settingsArray);
        openDownloadDialog(sheet2blob(sheet), '導出.xlsx');
},
 
<script>
    /**
     * 通用的打開下載對話框方法,沒有測試過具體兼容性
     * @param url 下載地址,也可以是一個blob對象,必選
     * @param saveName 保存文件名,可選
     */
    function openDownloadDialog(url, saveName)
    {
        if(typeof url == 'object' && url instanceof Blob)
        {
            url = URL.createObjectURL(url); // 創建blob地址
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的屬性,指定保存文件名,可以不要後綴,註意,file:///模式下不會生效
        var event;
        if(window.MouseEvent) event = new MouseEvent('click');
        else
        {
            event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
    }
 
    // 將一個sheet轉成最終的excel文件的blob對象,然後利用URL.createObjectURL下載
    function sheet2blob(sheet, sheetName) {
        sheetName = sheetName || 'Sheet1';
        var workbook = {
            SheetNames: [sheetName],
            Sheets: {}
        };
        workbook.Sheets[sheetName] = sheet;
        // 生成excel的配置項
        var wopts = {
            bookType: 'xlsx', // 要生成的文件類型
            bookSST: false, // 是否生成Shared String Table,官方解釋是,如果開啟生成速度會下降,但在低版本IOS設備上有更好的兼容性
            type: 'binary'
        };
        var wbout = XLSX.write(workbook, wopts);
        var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});
        // 字符串轉ArrayBuffer
        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
        return blob;
    }
</script>

總結:本篇主要記錄瞭

(1)前端上傳文件給後端multipart格式的方法 

(2)前端利用xls.js從excel文檔導入數據到json數組變量的方法

(3)前端利用xls.js將json數組導出到excel文檔下載的方法

上述代碼可以優化,暫時貼成這樣,以後有這樣的需求可以快速cv使用。

後續有時間可以多熟悉xls.js,Apache的POI和阿裡巴巴的EasyExcel,都是相關的內容

最後再貼一個用EasyExcel後臺將後臺生成的List數據導出的方法,可以用

window.location.href= [後臺導出的地址]  這種方式進行後端導出,註意設置response的格式

        try (ServletOutputStream out = response.getOutputStream()) {
            //這三行不可缺,否則會被前端解析成亂碼數據,而不是文件
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(sheetName, "UTF-8")
                    + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx");
 
            RowModel rowModel = excelService.getExcelModel(type);
            List<Map<String,Object>> list = rowModel.exportData(paramsMap);
            List rowModelList = JSONObject.parseArray(JSONObject.toJSONString(list),rowModel.getClass())
            ExcelWriter writer = EasyExcelFactory.getWriter(out);
            WriteSheet ws = new WriteSheet();
            ws.setSheetName(sheetName);
            ws.setClazz(rowModel.getClass());
            writer.write(rowModelList, ws);
            writer.finish();
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException();
        }

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: