Export of excel in java - based on PO

Table of contents

1. servlet class

2. Export processing class

first part

the second part

3.excel generation class


1. servlet class

The following is the exported servlet class, which inherits HttpServlet and implements the service method. The key code is the red part, excelBook = export(request);

It is based on the request parameter query results and the entity of the Workbook. After the response is set with two set methods, the output stream is obtained with getOutputStream  , and finally the excelBook is written to the output stream. I have seen it elsewhere.

This way of writing, using bufferedOutPut can improve a certain performance, but it can be ignored when there is less data. The following is the source code of the servlet class.


@Named("/servlet/exportBarometerServlet/export")
public class ExportBarometerServlet  extends HttpServlet
{
    private static final ILogger logger = JalorLoggerFactory.getLogger(ExportBarometerServlet.class);
    //excelName加上导出的时间为excel的名称
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    
    @Inject
    private IRiskBigScreenService riskBigScreenService;
    @Inject
    private IAosService AosService;
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
         Workbook excelBook = null;
        try
        {
            excelBook = export(request);
        }
        catch (WholeException e)
        {
            throw new ServletException(e);
        } catch (ApplicationException e) {
            e.printStackTrace();
        }
        
        if (excelBook != null)
        {
            String excelName = "IPMO-RiskProjectListMS";
            Date date = new Date();            
            response.setContentType("application/mx-excel");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + excelName+dateFormat.format(date)
                + ".xlsx\"");

            OutputStream out = null;
            try
            {
                out = response.getOutputStream();
                excelBook.write(out);
                out.flush();

            }
            finally
            {
                if (out != null)
                {
                    out.close();
                }
            }
        }
    }


2. Export processing class

first part

excelBook = export(request); The export() method is divided into two parts, the first part obtains the results in the form of List or Map according to the request (convert the format as needed)


private Workbook export(HttpServletRequest request) throws ApplicationException
    {
        String paramsJson = request.getParameter("paramsJson");
        Map map = null;
        try {
            map = JsonUtil.stringToObject(paramsJson, Map.class);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        XiAnQueryConditionVO vo = new XiAnQueryConditionVO();
        if( null != map)
        {
            vo.setPeriod(map.get("period").toString());
            vo.setOrgLevel(map.get("orgLevel").toString());
            vo.setOrgCode(map.get("orgCode").toString());
            vo.setL_proj_bu(map.get("l_proj_bu").toString());
        }


Get the json string from the request, convert it into a map, get the vo of the input parameter, call the service method to query the data, and choose whether to paginate according to your needs.


pagedResult = riskBigScreenService.findBarometerList(vo, pageVO);

List<XiAnBigScreenVO> list = pagedResult.getResult();


Convert the list to LinkedHashMap<String,List<String>>, this format is not HashMap because LinkedHashMap is ordered, and the order is consistent with the order of list in getMap(list); It can also be converted to List<List<String>> to ensure the order. Either way, it is for the sake of order when assigning values ​​to the excel table.


LinkedHashMap<String,List<String>> mapresult = getMap(list);


The String of LinkedHashMap<String, List<String>> can choose two types, one is the identifier that can determine the unique data, which comes from a certain field in a list.

The other is directly 1,2,3....


private LinkedHashMap<String, List<String>> getMap(List<XiAnBigScreenVO> resultlist) {
        LinkedHashMap<String, List<String>> map = new LinkedHashMap<>();
        for(XiAnBigScreenVO resultVO : resultlist)
        {
            List<String> list = new ArrayList<>();
            list.add(resultVO.getRegionName());
            list.add(resultVO.getRepofficeName());
            list.add(resultVO.getProjNum());
            list.add(resultVO.getProjName());
            list.add(resultVO.getProjLevel());
                            
            list.add(resultVO.getYtd_complete_rate());
            list.add(resultVO.getGap());
            list.add(resultVO.getYtd_aos_complete_rate());
            list.add(resultVO.getYtd_aos_gap());
            
            list.add(resultVO.getDe_lctd_cgp());
            list.add(resultVO.getDe_ytm_cgp());
            list.add(resultVO.getEx_lctd_ser_cost());
            list.add(resultVO.getEx_ytm_ser_cost());
            
            list.add(resultVO.getOperat_warning());
            //未有对应的服务出参
            list.add("");
            list.add("");
            list.add(resultVO.getProjProgressScorePercent());
            list.add(resultVO.getEhsScorePercent());
            
            list.add(resultVO.getCustomercomplaintsray());
            list.add(resultVO.getNontechnicalray());
            list.add(resultVO.getCyberaccidentsowner());
            list.add(resultVO.getCyberaccidentsother());
            list.add(resultVO.getItrmangementray());
            
            list.add(null !=resultVO.getQualitTechScore()?resultVO.getQualitTechScore()+"":"");
            list.add(null !=resultVO.getRationTechScore()?resultVO.getRationTechScore()+"":"");
            //list.add(null !=resultVO.getInternalControlScore()?resultVO.getInternalControlScore()+"":"");
            list.add(resultVO.getRiskTopItems());
            list.add(null !=resultVO.getCooperativeResourceScore()?resultVO.getCooperativeResourceScore()+"":"");
            map.put(resultVO.getProjNum(), list);
        }
        return map;
    }


 

the second part

The second part is wb = ExportBarometer.getXSSFWorkbook(mapresult, list, title1, title2); call the getXSSFWorkbook() method. It should be noted that the input parameters can be flexibly changed according to the needs. Generally speaking, the input parameters should have a title line , the query result List collection, sheetName.


XSSFWorkbook wb =null;
        //Arrays can also be used list    
         if ("zh_CN".equals(BaseSdcpUtils.getCurrentLanguage()))
         {              String[] title1 = {"Regional Department", "Representative Office", "Project Code", "Project Name","Project Level","Progress","","","","Operation","","","","","","","Quality"," ","Full","","","","","Technology","","Contract","Cooperation"}; String[] title2 = {"","",""              , "", "",

                    "Completion rate of improvement plan",
                    "actual completion value of improvement",
                    "completion rate of AOS improvement plan",
                    "actual completion value of AOS improvement",
                    "full-cycle forecast contribution gross profit (before provision) and budget deviation (deducting the impact of equipment) ",
                    "YTD forecast contribution gross profit (before provision) and budget deviation (deducting the impact of equipment)",
                    "ITD service cost exceeds budget",
                    "YTD service cost exceeds budget",
                    "ITD contribution gross deviation",
                    "Revenue completed Rate (YTD)",
                    "Operation Early Warning",
                    "SLA Compliance Rate",
                    "Network Availability Rate",
                    "Major Customer Complaints",
                    "Non-Technical Issues",
                    "Network Incident",
                    "MV Major Failure",
                    "Management Upgrade",
                    "Number of Unclosed Major Risks",
                    "Number of Unclosed Major Issues",
                    "Closed-loop Rate of Key Assumptions",
                    "(Cooperation)/Owned Leasing Resources Using Resource SLA (Owned & Leasing)"};
              wb = ExportBarometer.getXSSFWorkbook( mapresult,list,title1,title2);
         }else
         {              //Column title in English              String[] title1 = {"Region","RepOffice","Project Code","Project Name","Project Level"," Plan&Execution","","","","Operation","","","","","","","Quality","","Customer","","" ,"","","Technical","","Agreement","Cooperation"};              String[] title2 = {"","","","","",


                    "Transformation Plan Achievement Rate",
                    "Transformation Actual",
                    "AOS Transformation Plan Achievement Rate",
                    "AOS Transformation Actual",
                    "LIFECYCLE CGP Forecasts (Before Loss Provision)Compared With Latest Budgets (ex.equipment)",
                    "YTD LCGP Forecasts (Before Loss Provision)Compared With Latest Budgets (ex.equipment)",
                    "ITD Service Cost Over Lifecycle Budget",
                    "YTD Service Cost Over Annual Budget",
                    "ITD Contribution Gross Profit GAP",
                    "Revenue Achieving Rate (YTD)",
                    "Operation Alert",
                    "SLA Standard Rate",
                    "Network Availability",
                    "ok",
                    "Non-Tech Issue",
                    "Accident",
                    "MV Critical Incident",
                    "Management Escalation",
                    "Unclosed Major Risk Amount",
                    "Unclosed Major Issue Amount",
                    "MS Key Assumptions Closed Rate",
                    "TFPR /Timely Fulfillment of Partner Resources"};
             wb = ExportBarometer.getXSSFWorkbook(mapresult,list,title1,title2);
         }
        
        
        return wb;
        


3.excel generation class

Concrete implementation of the getXSSFWorkbook() method.

Side by side with XSSFWorkbook is HSSFWorkbook, depending on whether the excel format is xlsx or xls, one is 2007, and the other is 2003 version.


 

//The title line may be the first line or the second line, so the long pass parameter is not fixed
    public static XSSFWorkbook getXSSFWorkbook(LinkedHashMap<String, List<String>> map,List<XiAnBigScreenVO> listResult, String[]... title) {         XSSFWorkbook wb = new XSSFWorkbook();         String sheetName = "";         if ("zh_CN".equals(BaseSdcpUtils.getCurrentLanguage()))         {             sheetName = "MS Barometer Item Details";         }else         {             sheetName = "MsFindBarometerList";         }         XSSFSheet sheet = wb.createSheet(sheetName);         // Freeze pane         sheet.createFreezePane(0, 2);         XSSFRow row = sheet.createRow(0);         row.setHeightInPoints(30);









        





//        XSSFCellStyle style = wb.createCellStyle();
//      style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        XSSFCellStyle style = getColumnTopStyleX(wb);
        XSSFCell cell = null;
        for (int i = 0; i < title[0].length; i++) 
        {
            cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(title[0][i]);
            //9000对应34.5 ,则框架导出的宽度20.88对应5447
            sheet.setColumnWidth(i, 5447);
        }
        
        row = sheet.createRow(1);
        row.setHeightInPoints(40);
        for (int i = 0; i < title[1].length; i++) 
        {
            cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(title[1][i]);
        }
        
        for(int j=0;j<=4;j++)
        {             // merge cells , The four parameters represent the start row, end row, start column, end column             CellRangeAddress region = new CellRangeAddress(0,1,j,j);             sheet.addMergedRegion(region);         }         //Merge cells according to the title, modification trouble can be considered optimization         CellRangeAddress region = new CellRangeAddress(0,0,5,8);         sheet.addMergedRegion(region);                 region = new CellRangeAddress(0,0,9,15);         sheet.addMergedRegion(region);         region = new CellRangeAddress(0, 0,16,17);










        sheet.addMergedRegion(region);
        region = new CellRangeAddress(0,0,18,22);
        sheet.addMergedRegion(region);
        region = new CellRangeAddress(0,0,23,24);
        sheet.addMergedRegion(region);

        

        
        
        //Write entity data, the order of the strings in the list must be consistent with the order in the array strArray
        int i = 1;
        for (String str : map.keySet()) {             row = sheet.createRow((int) i + 1 );             List<String> list = map. get(str);

            // Create a cell and set the value
            for (int j = 0; j < title[0].length; j++) {                 XSSFCell datecell = row.createCell(j);                                 datecell.setCellValue(list.get(j));                 //Set the color for the cell                 setColor(i+1,j,datecell,listResult.get(i-1),wb); }             i             ++;         }                 return wb;     }









    


Sheet, row, and cell are three key objects. In addition to completing basic assignments, sometimes it is necessary to set cell size, color, font, font color size, etc., merge cells, freeze panes (generally freeze the header row), etc. The above is the most original version. You can freely encapsulate the method according to your personal habits to make the code look more organized and clear.

Guess you like

Origin blog.csdn.net/Spring_possible/article/details/90052085