首页 > 数据库 >下载数据库数据生成excel文件

下载数据库数据生成excel文件

时间:2024-07-09 15:44:46浏览次数:17  
标签:info log 数据库 excel wisdragon org import com 下载

下载数据库数据生成excel文件:
package com.wisdragon.controller.dataQuality;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wisdragon.comm.constant.Constant;
import com.wisdragon.model.comm.SysActnInfo;
import com.wisdragon.model.dataVerified.MetabaseField;
import com.wisdragon.model.dataVerified.MetabaseTable;
import com.wisdragon.model.dataVerified.Verified;
import com.wisdragon.service.comm.ISysActnInfoService;
import com.wisdragon.service.dataVerified.IMetabaseTableService;
import com.wisdragon.service.dataVerified.IVerifiedService;
import com.wisdragon.utils.JsonMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

import static com.wisdragon.utils.HttpClientUtil.postRestful;
import static com.wisdragon.utils.MbQuery.CreateJson;


/**
 * Description:excel数据校验下载结果
 * @author 韩波
 * @create 2018/10/19
 */
@Controller
@RequestMapping("/downloadExcel/")
public class DownloadTableToExcelController {
    private Workbook wb;
    private Sheet sheet;
    private Row row;
    private Cell cell;
    private CellStyle cellStyle;
    @Autowired
    IVerifiedService verifiedService;
    @Autowired
    IMetabaseTableService metabaseTableService;
    @Autowired
    ISysActnInfoService sysActnInfoService;
    private static final Logger log = LogManager.getLogger(DownloadTableToExcelController.class);
    @ResponseBody
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST},value = "downloadExcel/**")
    public int download(HttpServletResponse response, HttpSession session,
                        Integer id) {
        //从session中获得headerMap
        Map<String, String> headerMap = (Map<String, String>)session.getAttribute("headerMap");
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>...headerMap:"+headerMap);

        //通过id获取当前的一行verified信息
        Verified verified=verifiedService.getVerifiedById(id);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>...verified:"+new JsonMapper().toJson(verified));
        //通过tableId获得对应的数据库的id
        MetabaseTable table=metabaseTableService.getTableById(verified.getTableId());
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>...tableDB:"+table.getDbId());
        try {
            //获得表格的名称
            MetabaseTable tableName = metabaseTableService.getTableById(verified.getTableId());
            String fileName = new String( tableName.getName()+".xlsx");
            //获得要下载的表格中列的名称
            List<MetabaseField> colomnName=verifiedService.getAllTablesColomn(verified.getTableId());
            List<String> title = new ArrayList<>();
            for (MetabaseField name:colomnName) {
                title.add(name.getName());
            }
            //获得要下载的表格中的各个数据
            List<String> tableDate = new ArrayList<>();
            List<String> listError = new ArrayList<>();
            //创建查询的Sql语句对应的json对象                                    null==verified.getGenerateSql()
            org.json.JSONObject myJson = new org.json.JSONObject(CreateJson(tableName.getDbId(),null,Constant.MB_LOGINTYPE));
            //通过code获得对应的url
            SysActnInfo urlByCode = sysActnInfoService.getUrlByCode(Constant.MB_EXESQL);
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>:"+urlByCode.getActnUrl());
            //执行sql,获得查询到的数据
            String res3 = postRestful(urlByCode.getActnUrl(),headerMap,myJson.toString());
            //将得到的数据进行解析
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(res3).getAsJsonObject();
            JsonObject rows = jo.get("data").getAsJsonObject();
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>." + rows);
            Set<Map.Entry<String, JsonElement>> jsonSet = rows.entrySet();
            Iterator<Map.Entry<String, JsonElement>> it = jsonSet.iterator();
            while (it.hasNext()) {
                Map.Entry<String, JsonElement> jsonElementEntry = it.next();
                String key = jsonElementEntry.getKey();
                if (key!=null&&"rows".equals(key)) {
                    JsonElement je = jsonElementEntry.getValue();
                    JsonArray jsonArray = je.getAsJsonArray();
                    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>jsonArray.size():" + jsonArray.size());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JsonElement jtmp = jsonArray.get(i);
                        JsonArray jsTmp = jtmp.getAsJsonArray();
                        for (int j = 0; j < jsTmp.size()-1; j++) {
                            JsonElement jetmp = jsTmp.get(j);
                            tableDate.add(jetmp.toString().replace("\"",""));
                            log.info("===i:" + i + "===j:" + j + "-----jetmp:" + jetmp);
                        }
                        log.info("-----jtmp" + jtmp);
                        String sError = jsTmp.toString();
                        String element =sError.substring(sError.lastIndexOf(",")+1,sError.length()-1);
                        log.info("============================================element:" + element);
                        listError.add(element);
                        log.info("============================================listError:" + listError);


                    }
                }
            }
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>red:"+tableDate);
            createExcel(title, tableDate);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            wb.write(baos);
            response.addHeader("Content-Disposition",   "attachment;filename="+ URLEncoder.encode(fileName, "GBK"));
            response.setContentLength(baos.size());
            ServletOutputStream sos = response.getOutputStream();
            baos.writeTo(sos);
            baos.close();
            sos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public void createExcel(List<String> titleList, List<String> redList) {
        wb = new XSSFWorkbook();
        sheet = wb.createSheet();
        //行号
        int startRow = 0;
        int startcol = 0;
        //列号
        int endcol = 0;
        //字体
        Font font = wb.createFont();
        //字体高度
        font.setFontHeightInPoints((short)20);
        //字体颜色
        font.setColor(Font.COLOR_NORMAL);
        //单元格
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setWrapText(true);
        endcol = titleList.size();
        log.info(titleList.toString());
        startRow = addData(titleList, endcol, endcol, startRow);
        log.info(startRow);
        startRow = addData(redList, endcol, endcol, startRow);
        log.info(startRow);

    }
    public int addData(List<String> list, int start, int end, int srow) {
        XSSFDataValidationHelper xdvh;
        XSSFDataValidationConstraint xdvC;
        CellRangeAddressList reg;
        DataValidation dv;
        for(int i=0 ; i<list.size(); i++) {
            if(start == end) {
                start = 0;
                row = sheet.createRow(srow++);
            }
            cellStyle = wb.createCellStyle();
            if(Integer.toString(2).equals(list.get(i))) {
                cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
                cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                xdvh = new XSSFDataValidationHelper((XSSFSheet) sheet);
                xdvC = (XSSFDataValidationConstraint) xdvh.createCustomConstraint("error");
                reg = new CellRangeAddressList(srow-1, srow-1, i, i);
                dv = xdvh.createValidation(xdvC, reg);
                dv.createPromptBox("错误提示:","错误内容");
                dv.setShowPromptBox(true);
                sheet.addValidationData(dv);
            }
            cell = row.createCell(start++);
            cell.setCellValue(list.get(i));
            cell.setCellStyle(cellStyle);
        }
        return srow;
    }

}

 

 

 

声明:此博客为个人学习之用,如与其他作品雷同,纯属巧合,转载请指明出处!

 

标签:info,log,数据库,excel,wisdragon,org,import,com,下载
From: https://www.cnblogs.com/zhihuifan10/p/18292060

相关文章

  • 上传excel到数据库
    上传excel到数据库:packagecom.wisdragon.controller.dataQuality;importcom.wisdragon.comm.constant.Constant;importcom.wisdragon.controller.common.BaseController;importcom.wisdragon.model.dataQuality.RuleBase;importcom.wisdragon.model.dataQuality.RuleV......
  • Excel表格如何免费转成PDF的3种方法
    很多时候我们会将各种各样的文档转换成pdf的格式,然后发送给别人,因为pdf格式在阅读上既能保持很好的效果,又不会编辑到里面的内容,那么要怎么excel表格转换成pdf呢?方法一:使用Excel软件自带的“另存为”功能大多数版本的MicrosoftExcel都提供了将文档另存为PDF的功能,这是最简单直接......
  • 数据库范式
    1范式的基本概念设计关系数据库时,遵从不同的规范要求,设计出合理的关系型数据库,这些不同的规范要求被称为不同的范式,各种范式呈递次规范,越高的范式数据库冗余越小。没有冗余的数据库未必是最好的数据库,有时为了提高运行效率,就必须降低范式标准,适当保留冗余数据。函数依赖比如......
  • sybase数据库恢复
    Sybase数据库的恢复过程可以因不同的故障类型和数据损坏程度而有所不同。以下是一个一般性的恢复步骤和策略,但请注意,这些方法并不能保证百分之百的成功,特别是在数据严重损坏或没有适当备份的情况下。一、备份数据在进行任何恢复操作之前,首先确保对现有的数据库和相关文件进行完......
  • Interbase数据库修复
    一、准备阶段备份数据库:在进行任何修复操作之前,务必先对受损的数据库进行完整备份。这是防止在修复过程中数据进一步丢失或损坏的重要步骤。使用Interbase提供的备份工具(如gbak)或第三方备份工具进行备份。断开连接:确保没有任何程序或用户正在访问或使用该数据库,以避免在修复......
  • Firebird数据库修复
    一、前期准备断开数据库连接:确保所有与Firebird数据库的连接都已断开,避免在修复过程中发生数据冲突或损坏。备份数据库:在进行任何修复操作之前,使用Firebird提供的gbak工具或其他备份工具对数据库进行完整备份。备份文件将在修复过程中起到关键作用,以防修复失败导致数据丢失。......
  • InterBase数据库文件损坏的修复方法
    InterBase数据库是一种中级数据库,它短小精悍免维护,可以满足百万记录级别的数据库应用,又有开放源码版本,个人认为是一种比较适合中小型数据库应用环境的数据库管理系统(DBMS)。Delphi内建了对InterBase数据库的支持,因此用Delphi编写以InterBase为后台数据库的软件很是方便。在实际应......
  • 使用Mybatis框架操作数据库
    --------------idea中创建springboot项目引入Mybatis框架-----------------1、新建空项目2.创建模块3.选择springboot版本,添加mybatisframework框架和Mysqldriver驱动 4.删除多余文件 5.选择父工程中选择spring-boot版本6.选择依赖版本号(1)mybatis的起步依赖......
  • 服务器数据库OAERP报错
    一、常见原因网络问题:网络延迟、网络阻塞或网络故障都可能导致数据库连接不稳定或中断。防火墙或路由器的设置不当也可能阻止ERP系统与数据库之间的正常通信。数据库配置问题:数据库服务器的IP地址、端口号、用户名和密码等配置信息错误或不一致。数据库服务器的配置参数设置......
  • 如何解决数据库配置问题
    识别配置问题收集错误信息:首先,收集数据库配置过程中出现的所有错误信息和日志。这些信息通常会在数据库服务器的日志文件、系统日志或应用程序日志中记录。分析问题性质:分析错误信息以确定问题的性质。这可能涉及检查数据库连接问题、性能瓶颈、配置参数不当等。检查配置文......