java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java springboot接口导出txt

java、springboot 接口导出txt方式

作者:通尼渣渣

这篇文章主要介绍了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();
        }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文