数据库信息生成csv并下载

public Result downModelParams(String uuid, HttpServletResponse response) {
if (StringUtils.isBlank(uuid)) {
throw new IllegalArgumentException(“参数不能为空”);
}
AiModel aiModel = aiModelMapper.selectModelByUuid(uuid);
if (aiModel == null || aiModel.getParams() == null) {
throw new IllegalArgumentException(“模型参数为空”);
}
Map<String, String> map = new LinkedHashMap<>();
map.put(“1”, “ID”);
map.put(“2”, “标题”);
map.put(“3”, “数据类型”);
List list = new ArrayList<>();
String params = aiModel.getParams();
//保持参数顺序一致
LinkedHashMap<String, Object> json = JSON.parseObject(params, LinkedHashMap.class, Feature.OrderedField);
JSONObject paramsJson = new JSONObject(true);
paramsJson.putAll(json);
for (String key : paramsJson.keySet()) {
Map<String, String> paramsMap = new LinkedHashMap<>();
paramsMap.put(“1”, key);
paramsMap.put(“2”, key);
if (paramsJson.getString(key).equals(“int”)) {
paramsMap.put(“3”, “Integer”);
} else if (paramsJson.getString(key).equals(“double”)) {
paramsMap.put(“3”, “Double”);
} else if (paramsJson.getString(key).equals(“date”)) {
paramsMap.put(“3”, “Date”);
} else if (paramsJson.getString(key).equals(“long”)) {
paramsMap.put(“3”, “Long”);
} else if (paramsJson.getString(key).equals(“boolean”)) {
paramsMap.put(“3”, “Boolean”);
} else {
paramsMap.put(“3”, “String”);
}
list.add(paramsMap);
}
try {
CsvUtil.exportDataFile(response, list, map, modelParamsPath, aiModel.getModelName());
} catch (IOException e) {
logger.error(e.getLocalizedMessage(),e);
throw new IllegalArgumentException(“下载失败”);
}
return Result.newSuccess();
}

package com.beagledata.gaea.workbench.common;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.;
import java.net.URLEncoder;
import java.util.
;

/**

  • Created by mahongfei on 2019/3/21.
    /
    public class CsvUtil {
    /
    *
    • @Author: mahongfei

    • @description: 生成并下载csv文件
      */
      public static void exportDataFile(HttpServletResponse response,
      List exportData,
      Map<String, String> map,
      String outPutPath,
      String fileName) throws IOException{
      File csvFile = null;
      BufferedWriter csvFileOutputStream = null;
      try {
      File file = new File(outPutPath);
      if (!file.exists()) {
      file.mkdirs();
      }
      //定义文件名格式并创建
      csvFile = new File(outPutPath + fileName+".csv");
      if(csvFile.exists()){
      csvFile.delete();
      }
      csvFile.createNewFile();
      // UTF-8使正确读取分隔符","
      //如果生产文件乱码,windows下用gbk,linux用UTF-8
      csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), “UTF-8”), 1024);
      //写入前段字节流,防止乱码
      csvFileOutputStream.write(getBOM());
      // 写入文件头部
      for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext()? {
      java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
      csvFileOutputStream.write((String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : “” );
      if (propertyIterator.hasNext()) {
      csvFileOutputStream.write(",");
      }
      }
      csvFileOutputStream.newLine();
      // 写入文件内容
      for (Iterator iterator = exportData.iterator(); iterator.hasNext()? {
      Object row = (Object) iterator.next();
      for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext()? {
      java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
      String str=row!=null?((String)((Map)row).get( propertyEntry.getKey())):"";
      if(StringUtils.isEmpty(str)){
      str="";
      }else{
      str=str.replaceAll(""","""");
      if(str.indexOf(",")>=0){
      str="""+str+""";
      }
      }
      csvFileOutputStream.write(str);
      if (propertyIterator.hasNext()) {
      csvFileOutputStream.write(",");
      }
      }
      if (iterator.hasNext()) {
      csvFileOutputStream.newLine();
      }
      }
      csvFileOutputStream.flush();
      } catch (Exception e) {
      e.printStackTrace();
      } finally {
      try {
      csvFileOutputStream.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      }
      InputStream in = null;
      try {
      in = new FileInputStream(outPutPath+fileName+".csv");
      int len = 0;
      byte[] buffer = new byte[1024];

       OutputStream out = response.getOutputStream();
       response.reset();
      
       response.setContentType("application/csv;charset=UTF-8");
       response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(fileName+".csv", "UTF-8"));
       response.setCharacterEncoding("UTF-8");
       while ((len = in.read(buffer)) > 0) {
           out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
           out.write(buffer, 0, len);
       }
         out.close();
      

      } catch (FileNotFoundException e) {

      } finally {
      if (in != null) {
      try {
      in.close();
      } catch (Exception e) {
      throw new RuntimeException(e);
      }
      }
      }

}

public static String getBOM() {
byte b[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
return new String(b);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值