POI合併單元格的使用

 private void cellRange(HSSFSheet sheet, HSSFRow row, HSSFCellStyle cellStyle, String cellVal, int firstRow, int lastRow, short fistCol, short lastCol) {
        HSSFCell cell = row.createCell(fistCol);
        cell.setCellValue(cellVal);
        cell.setCellStyle(cellStyle);
        CellRangeAddress cellRange = new CellRangeAddress(firstRow, lastRow, fistCol, lastCol);
        sheet.addMergedRegion(cellRange);
        setRegionStyle(sheet, cellRange, cellStyle);
    }

    public void setRegionStyle(HSSFSheet sheet, CellRangeAddress region, HSSFCellStyle cs) {
        RegionUtil.setBorderBottom(cs.getBorderBottom(), region, sheet);//下邊框
        RegionUtil.setBorderLeft(cs.getBorderLeft(), region, sheet);     //左邊框
        RegionUtil.setBorderRight(cs.getBorderRight(), region, sheet);    //右邊框
        RegionUtil.setBorderTop(cs.getBorderTop(), region, sheet);      //上邊框
    }

注意,合併單元格並賦予合併後的單元格的樣式時,必須將所合併的單元格“全部創建”!!!!否則單元格的格式會缺失!!!

excel 轉html

private String toHtml(HSSFWorkbook workbook) throws TransformerException, IOException, ParserConfigurationException {
        ExcelToHtmlConverter ethc = new ExcelToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        ethc.setOutputColumnHeaders(false);
        ethc.setOutputRowNumbers(false);
        ethc.processWorkbook(workbook);

        Document htmlDocument = (Document) ethc.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();

        String htmlStr = new String(out.toByteArray());

        htmlStr = htmlStr.replace("<h2>Sheet1</h2>", "")
                .replace("<h2>Sheet2</h2>", "")
                .replace("<h2>Sheet3</h2>", "")
                .replace("<h2>Sheet4</h2>", "")
                .replace("<h2>Sheet5</h2>", "");

        return htmlStr;
    }

excel轉html預覽時,單元格函數未進行計算,則需要加上如下代碼,重新聲明該單元格爲函數

FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
for (int i = 0; i <  sheet.getPhysicalNumberOfRows(); i++) {
   HSSFRow row = sheet.getRow(i);
    for (int j = 0; j < row.getPhysicalNumberOfCells() ; j++) {
        HSSFCell cell = row.getCell(j);
        if(cell.getCellType()==CellType.FORMULA.getCode()){
            evaluator.evaluateFormulaCell(cell);
        }
    }
}
sheet.setForceFormulaRecalculation(true);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章