工作中一些java代码总结

1.http

get请求

public static String doGet(String url, Map<String, String> params, Map<String, String> headers){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response=null;
        String result="";
     try{
         if(params!=null&&params.size()!=0){
             StringBuffer suffix = new StringBuffer("?");
             for(String key:params.keySet()){
                 suffix.append(key);
                 suffix.append("=");
                 suffix.append(params.get(key));
                 suffix.append("&");
             }
             suffix.deleteCharAt(suffix.length()-1);
             url=url+suffix.toString();
         }
         HttpGet httpGet = new HttpGet(url);
         if(headers!=null){
             for(String key:headers.keySet()) {
                 httpGet.addHeader(key,headers.get(key));
             }
         }
         response = client.execute(httpGet);
         result= EntityUtils.toString(response.getEntity());
     }catch (IOException e) {
         e.printStackTrace();
     }finally {
         try{
             if (response != null) {
                 response.close();
             }
             if (client != null) {
                 client.close();
             }
         }catch (IOException e){
             e.printStackTrace();
         }
     }
        return result;
    }

post请求

public static String doPost(String url, Map<String, String> params, Map<String, String> headers){
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response=null;
    String result="";
   try{
       HttpPost httpPost = new HttpPost(url);

       if(headers!=null&&headers.size()!=0){
           for(String key:headers.keySet()){
               httpPost.addHeader(key,headers.get(key));
           }
       }
       if(params!=null&&params.size()!=0){
           if(headers.get("Content-Type")!=null&&headers.get("Content-Type").contains("json")){
               StringEntity s = new StringEntity(JSONUtils.toJSONString(params),"UTF-8");
               s.setContentEncoding("UTF-8");
               s.setContentType(headers.get("Content-Type"));//发送json数据需要设置contentType
               httpPost.setEntity(s);
           }else {
               List<NameValuePair> list = new LinkedList<>();
               for(String key:params.keySet()){
                   BasicNameValuePair param = new BasicNameValuePair(key, params.get(key));
                   list.add(param);
               }
               UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
               httpPost.setEntity(entityParam);
           }

       }
       response = client.execute(httpPost);
       HttpEntity entity = response.getEntity();
       result = EntityUtils.toString(entity);
   }catch (Exception e){
       e.printStackTrace();
   }

    return result;
}

put

public static String doPut(String url,Map<String,String> headers, String jsonStr) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse httpResponse = null;
    HttpPut httpPut = new HttpPut(url);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
    httpPut.setConfig(requestConfig);
    if(headers!=null&&headers.size()!=0){
        for(String key:headers.keySet()){
            httpPut.addHeader(key,headers.get(key));
        }
    }
    try {
        httpPut.setEntity(new StringEntity(jsonStr,"UTF-8"));
        httpResponse = httpClient.execute(httpPut);
        HttpEntity entity = httpResponse.getEntity();
        String result = EntityUtils.toString(entity);
        return result;
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (null != httpClient) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

传图片

public static String getSuffix(final MultipartFile file){
    if(file == null || file.getSize() == 0){
        return null;
    }
    String fileName = file.getOriginalFilename();
    return fileName.substring(fileName.lastIndexOf(".")+1);
}
public static JSONObject uploadFile(String urlStr, MultipartFile file, String token) throws IOException {

    // 后缀
    String suffix = getSuffix(file);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(urlStr);

    uploadFile.setHeader("Authorization",token);
    DecimalFormat df = new DecimalFormat("#.##");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    //  HTTP.PLAIN_TEXT_TYPE,HTTP.UTF_8
    builder.addTextBody("name", file.getOriginalFilename(), ContentType.create("multipart/form-data", Consts.UTF_8));
    builder.addTextBody("size", df.format((double) file.getSize() / 1024), ContentType.TEXT_PLAIN);
    builder.addTextBody("suffix", suffix, ContentType.TEXT_PLAIN);

    // 把文件加到HTTP的post请求中
    // String filepath = "/user/test/123.png"
    // File f = new File(filepath);
    builder.addBinaryBody(
            "file",
            file.getInputStream(),
            // new FileInputStream(f),
            ContentType.APPLICATION_OCTET_STREAM,
            file.getOriginalFilename()
    );

    HttpEntity multipart = builder.build();
    uploadFile.setEntity(multipart);
    CloseableHttpResponse response = httpClient.execute(uploadFile);
    HttpEntity responseEntity = response.getEntity();
    String sResponse= EntityUtils.toString(responseEntity, "UTF-8");
    JSONObject jsonObject = JSONObject.parseObject(sResponse);
    return jsonObject;
}

对应前端图片

 file = this.dataURLtoFile(this.profile, 'icon.jpg')
 
     dataURLtoFile (dataurl, filename) {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    }

在这里插入图片描述

导出EXCEL表

public Map<String, String> importPowerDistribution(HttpServletResponse response, HttpServletRequest request, String userName, MultipartFile file, String dataTime) {
        Map<String, String> result = new HashMap<>();
        result.put("msg", "电力分配基础表导入成功");
        result.put("status", "200");
        try {
            powerDistributionBasisService.importPowerDistribution(response, request, userName, file, dataTime, DataTypeEnum.switchType("month"));
        } catch (Exception e) {
            result.put("msg", "电力分配基础表导入失败[" + e.getMessage() + "]");
            result.put("status", "400");
        }

        return result;
    }
@Transactional(rollbackFor = Exception.class)
@Synchronized
@Override
public void importPowerDistribution(HttpServletResponse response, HttpServletRequest request, String userName, MultipartFile file, String dataTime, DataTypeEnum dataType) throws Exception {
    InputStream fileInputStream = file.getInputStream();
    Workbook workbook;
    workbook = WorkbookFactory.create(fileInputStream);
    int numberOfSheets = workbook.getNumberOfSheets();
    String readTime = DateUtil.StrTime(dataTime);//这月27号的00:00:00
    String beforeTime = DateUtil.beforeReadTime(readTime);//这月26号的23:00:00
    String lastMonthTime = DateUtil.lastMonthReadTime(readTime);//上一月的27号的00:00:00
    String lastMonthBefore = DateUtil.beforeReadTime(lastMonthTime);//String类型:上一月26号的23:00:00
    List<ElectricEnergyDevice> electricEnergyDevices = electricEnergyDeviceRepository.findAll();
    Map<String, ElectricEnergyDevice> deviceHashMap = new HashMap<>();
    Map<String, EnergyDeviceCollection> deviceCollectionHashMap = collections(beforeTime, readTime);
    for (ElectricEnergyDevice device : electricEnergyDevices) {
        deviceHashMap.put(device.getDeviceName(), device);
    }
    for (int s = 0; s < numberOfSheets; s++) {
        Sheet sheet = workbook.getSheetAt(s);
        if (sheet == null) {
            continue;
        }
        if (sheet != null) {
            int rowNos = sheet.getLastRowNum();
            for (int i = 1; i <= rowNos; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    ExcelUtil.setCellType(row);
                    //电能表名称0/用电单位1/工程名称2/电压3/上月表码4/本月表码5/码差6/倍率7/抄见电量8/分摊线变损9/电量合计10/备注11
                    String deviceName = "";
                    String projectName = "";
                    String voltage = "";
                    String lastMonthEnergyConsumption = "";
                    String energyConsumption = "";
                    String ratio = "";
                    String description = "";
                    if (null != row.getCell(5) && !"".equals(row.getCell(5))) {
                        energyConsumption = (String) ExcelUtil.subString((row.getCell(5)).getStringCellValue());
                    }
                    if (null != row.getCell(4) && !"".equals(row.getCell(4))) {
                        lastMonthEnergyConsumption = (String) ExcelUtil.subString((row.getCell(4)).getStringCellValue());
                    }
                  
                    if (null != row.getCell(0) && !"".equals(row.getCell(0))) {
 
                        deviceName = (String) ExcelUtil.subString((row.getCell(0)).getStringCellValue());
                        ElectricEnergyDevice electricEnergyDevice = deviceHashMap.get(deviceName);
                        if (null != electricEnergyDevice) {
                            //更新上月数据
                            if (null != lastMonthEnergyConsumption && !lastMonthEnergyConsumption.equals("")) {
                                updateLastMonth(lastMonthBefore, lastMonthTime, electricEnergyDevice, userName, Double.parseDouble(lastMonthEnergyConsumption));
                            }
                            //更新本月数据
                            EnergyDeviceCollection energyDeviceCollection = deviceCollectionHashMap.get(electricEnergyDevice.getDeviceCode());
                            if (null != energyConsumption && !energyConsumption.equals("") && null != lastMonthEnergyConsumption && !lastMonthEnergyConsumption.equals("")) {
                                if (Double.parseDouble(energyConsumption) < Double.parseDouble(lastMonthEnergyConsumption)) {
                                    throw new Exception("上月表码不能大于本月表码");
                                }
                                updateData(beforeTime, electricEnergyDevice, userName, energyDeviceCollection, Double.parseDouble(energyConsumption), Double.parseDouble(lastMonthEnergyConsumption));
                            }
                        } else {
                            continue;
                        }
                    }
                }
            }
        }
    }
    String num= updateDataCompletionRate(beforeTime, readTime);
    updatePowerBasis(userName, dataTime,num);
}
@Override
public void export(HttpServletResponse response, HttpServletRequest request, String dataTime) throws Exception {
    String agent = request.getHeader("USER-AGENT").toLowerCase();
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    String fileName = dataTime.split("\\.")[0] + "年" + dataTime.split("\\.")[1] + "月" + "电力分配基础表.xls";
    String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
    if (agent.contains("firefox")) {
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-disposition",
                "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
    } else {
        response.setHeader("content-disposition", "attachment;filename=" + encodeFileName);
    }
    HSSFWorkbook wb = new HSSFWorkbook();
    Map<String, List<List<String>>> contents = new HashMap<>();
    List<List<String>> content = new ArrayList<>();
    List<String> rows = new ArrayList<>();
    rows.add("电能表名称");
    rows.add("用电单位");
    rows.add("工程名称");
    rows.add("电压");
    rows.add("上月表码(kw·h)");
    rows.add("本月表码(kw·h)");
    rows.add("码差");
    rows.add("倍率");
    rows.add("抄见电量");
    rows.add("分摊线变损");
    rows.add("电量合计");
    rows.add("备注");
    content.add(rows);
    String readTime = DateUtil.StrTime(dataTime);//String类型:这月27号的00:00:00
    String beforeTime = DateUtil.beforeReadTime(readTime);//String类型:这月26号的23:00:00
    Map<String, EnergyDeviceCollection> collectionsHashMap = collections(beforeTime, readTime);
    List<ElectricEnergyDevice> electricEnergyDevices = electricEnergyDeviceRepository.findAll();
    for (ElectricEnergyDevice device : electricEnergyDevices) {
        EnergyDeviceCollection energyDeviceCollection = collectionsHashMap.get(device.getDeviceCode());
        List<String> detail = new ArrayList<>();
        detail.add(0, device.getDeviceName());
        detail.add(1, device.getAssertName());
        detail.add(2, device.getProjectName());
        if (null == device.getVoltage()) {
            detail.add(3, null);
        } else {
            detail.add(3, device.getVoltage().toString());
        }
        if (null == energyDeviceCollection.getLastMonthEnergyConsumption()) {
            detail.add(4, null);
        } else {
            detail.add(4, energyDeviceCollection.getLastMonthEnergyConsumption().toString());
        }
        if (null == energyDeviceCollection.getEnergyConsumption()) {
            detail.add(5, null);
        } else {
            detail.add(5, energyDeviceCollection.getEnergyConsumption().toString());
        }
        if (null == energyDeviceCollection.getEnergyConsumptionGap()) {
            detail.add(6, null);
        } else {
            detail.add(6, energyDeviceCollection.getEnergyConsumptionGap().toString());
        }
        if (null == device.getRatio()) {
            detail.add(7, null);
        } else {
            detail.add(7, device.getRatio().toString());
        }
        if (null == energyDeviceCollection.getSumRatio()) {
            detail.add(8, null);
        } else {
            detail.add(8, energyDeviceCollection.getSumRatio().toString());
        }
        if (null == energyDeviceCollection.getRatioLine()) {
            detail.add(9, null);
        } else {
            detail.add(9, energyDeviceCollection.getRatioLine().toString());
        }
        if (null == energyDeviceCollection.getSum()) {
            detail.add(10, null);
        } else {
            detail.add(10, energyDeviceCollection.getSum().toString());
        }
        detail.add(11, energyDeviceCollection.getDescription());
        content.add(detail);
    }
    contents.put("第一页", content);
    ExcelUtil.writeExcel(wb, contents, response, request, rows, fileName);
}

ExcelUtil

package com.cloudiip.backend.data.sample.jpa.util;

import com.microsoft.schemas.office.visio.x2012.main.CellType;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.persistence.Convert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * @author gqy
 * @description: 导出excel
 * @date 2019/6/13 13:43
 */
public class ExcelUtil {

    /**
     * 导出excel
     *
     * @param contents 导出内容
     * @param columns  列名
     */
    public static void writeExcel(HSSFWorkbook workbook,
    Map<String, List<List<String>>> contents,
                                  HttpServletResponse response, 
                                  HttpServletRequest request, List<String> columns,
                                  String fileName) {
        for (Map.Entry<String, List<List<String>>> entry : contents.entrySet()) {
            HSSFSheet sheet = workbook.createSheet(entry.getKey());
//            sheet.autoSizeColumn(1, true);
            autoSizeColumn(sheet, columns);
            for (int i = 0; i < entry.getValue().size(); i++) {
                HSSFRow row = sheet.createRow(i);
                List<String> list = entry.getValue().get(i);
                for (int j = 0; j < list.size(); j++) {
                    HSSFCell cell = row.createCell(j);
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    cell.setCellValue(list.get(j));
                }
            }
        }
        output(response, workbook, fileName);
    }

    public static void output(HttpServletResponse response, 
    Workbook workbook, String fileName) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition",
             "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            // 解决输出文件名乱码问题
            OutputStream output = response.getOutputStream();
            workbook.write(output);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置单元格内容类型
     *
     * @param row
     */
    public static void setCellType(Row row) {
        for (int i = 0; i <= 20; i++) {
            if (null != row.getCell(i))
                row.getCell(i).setCellType(HSSFCell.CELL_TYPE_STRING);
        }
    }

    /**
     * 数字自动带“.0”处理方法
     *
     * @param cellData
     */
    public static Object subString(String cellData) {
        while (cellData.endsWith(".0")) {
            cellData =
                    cellData.substring(0,
                            cellData.length() - 2);
        }

        if (null == cellData) {
            return "";
        }
        return cellData;
    }

    /**
     * 列名宽度自适应设置(适用于中文)
     */
    public static void autoSizeColumn(HSSFSheet sheet, List<String> columns) {
        for (String column : columns) {
            sheet.setColumnWidth(1, column.getBytes().length * 2 * 256);
        }
    }

    /**
     * 请求头设置
     */
    public static void setStyle(HttpServletResponse response,
     HttpServletRequest request, String fileName) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
        String agent = request.getHeader("USER-AGENT").toLowerCase();
        if (agent.contains("firefox")) {
            response.setCharacterEncoding("utf-8");
            response.setHeader("content-disposition",
                    "attachment;filename=" + 
                    new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
        } else {
            response.setHeader("content-disposition", 
            "attachment;filename=" + encodeFileName);
        }
    }

    /**
     * @param filePath 需要读取的文件路径
     * @param column   指定需要获取的列数,例如第一列 1
     * @param startRow 指定从第几行开始读取数据
     * @param endRow   指定结束行
     * @return 返回读取列数据的set
     */
    public static List<String> getColumnSet(String filePath,
     int column, int startRow, int endRow) {
        Workbook wb = readExcel(filePath); //文件
        Sheet sheet = wb.getSheetAt(0); //sheet
        int rownum = sheet.getPhysicalNumberOfRows(); //行数
        Row row = null;
        List<String> result = new ArrayList<>();
        String cellData = null;
        if (wb != null) {
            for (int i = startRow - 1; i < endRow; i++) {
                row = sheet.getRow(i);
                if (row != null) {
                    cellData = (String) getCellFormatValue(
                    row.getCell(column - 1));
                    result.add(cellData.replaceAll(" ", ""));
                } else {
                    break;
                }
            }
        }
        return result;
    }

    //读取excel
    public static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    public static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            //判断cell类型
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC: {
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                     //将数值型cell设置为string型
                    cellValue = cell.getStringCellValue();
                    break;
                }
                case HSSFCell.CELL_TYPE_FORMULA: {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                }
                case HSSFCell.CELL_TYPE_STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值