JXLS模板導出EXCEL

   最近作要作一些報表導出的功能,因爲表格內容比較複雜,直接生成excel比較麻煩,因此採用模板的方式來作,惋惜本身不瞭解,也證實了本身技術有多差!經過屢次資料,終於找到了適合本身的方法。特此記錄,方便之後查找。java

   maven用到的包web

 <dependency>
    <groupId>net.sf.jxls</groupId>
    <artifactId>jxls-core</artifactId>
    <version>1.0.6</version>
</dependency>
<dependency>
    <groupId>net.sf.jxls</groupId>
    <artifactId>jxls-reader</artifactId>
    <version>1.0.6</version>
</dependency>

Service代碼app

public void exportChargeCount(String yearMonth, String buildId, HttpServletRequest request,HttpServletResponse response) 
    {
        String templateFile = request.getSession().getServletContext().getRealPath("/")+"/doc/reportTmp/billingInfo.xls";
        Date date = BillingDateUtil.getBillingEndTime(Integer.valueOf(yearMonth.substring(0, 4)),Integer.valueOf(yearMonth.substring(5, 7)));
        String buildName = dataCenter.getBuildInfoById(buildId).getBuildName();
        String fileName = buildName+"("+yearMonth+")客戶彙總報表.xls";
        List<ChargeCountVO> list =  this.reportDao.getChargeCount(DateUtil.getFormatNormal(date), buildId);
        Map<String, Object> context = new HashMap<>();
        XLSTransformer transformer = new XLSTransformer();
        
        float sumMoney = 0;
        for (ChargeCountVO chargeCountVO : list) {
            sumMoney += chargeCountVO.getEnergyMoney();
        }
        
        context.put("billingList", list);
        context.put("sumMoney", sumMoney);
        context.put("billingDate", yearMonth);
        context.put("buildName",buildName );
        
        try {
            response.setContentType("application/vnd.ms-excel");  
            response.setHeader("Content-disposition", "p_w_upload;filename="+new String( fileName.getBytes("GBK"), "ISO8859-1" ));
            Workbook workbook =  transformer.transformXLS(new FileInputStream(templateFile), context);
            OutputStream ouputStream = response.getOutputStream();
            workbook.write(ouputStream);  
            ouputStream.flush();  
            ouputStream.close();  
        } catch (ParsePropertyException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

採用鍵值對的形式maven


xls模板ide

wKioL1RzK8mwkiuHAAKM9OX8rJo428.jpg


導出效果ui

wKiom1RzK-yCIFCJAAZ2YZtagFI834.jpg


你們可能會遇到的問題this

一、web下載中文名稱不顯示的問題lua

二、模板使用公式,下載下來不計算的問題spa

三、合併單元格的問題excel

下面逐一解答

一、中文字符轉碼

response.setHeader("Content-disposition", "p_w_upload;filename="+new String( fileName.getBytes("GBK"), "ISO8859-1" ));

二、從新加載模板公式(通用方法)

 /**
     * 
     * 從新設置單元格計算公式
     * 
     * */
    private void resetCellFormula(HSSFWorkbook wb)
    {
        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(wb);
        int sheetNum = wb.getNumberOfSheets();
        for (int i = 0; i < sheetNum; i++)
        {
            HSSFSheet sheet = wb.getSheetAt(i);
            int rows = sheet.getLastRowNum() + 1;
            for (int j = 0; j < rows; j++)
            {
                HSSFRow row = sheet.getRow(j);
                if (row == null)
                    continue;
                int cols = row.getLastCellNum();
                for (int k = 0; k < cols; k++)
                {
                    HSSFCell cell = row.getCell(k);
                    // if (cell != null)
                    // System.out.println("cell["+j+","+k+"]=:"+cell.getCellType());
                    if (cell == null)
                        continue;
                    if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA)
                    {
                        cell.setCellFormula(cell.getCellFormula());
                        // System.out.println("----公式:"+cell.getCellFormula());
                        cell = e.evaluateInCell(cell);
                        // System.out.println("-----------"+cell.getNumericCellValue());
                    }
                }
            }
        }
    }

使用方法

wKiom1RzLbbgWz7rAAL_DEUlXHU432.jpg

三、合併單元格

HSSFWorkbook  workbook = (HSSFWorkbook )transformer.transformXLS(new FileInputStream(templateFile), context);
HSSFSheet sheet = workbook.getSheetAt(0); 
sheet.addMergedRegion(new CellRangeAddress(起始行號,截至行號,起始列號,截至列號));

四個參數均從0開始


以上就是最近的總結。若是有問題你們能夠互相交流。

相關文章
相關標籤/搜索