POI excel匯出,poiexcel匯出

來源:互聯網
上載者:User

POI excel匯出,poiexcel匯出

******************************************************************************************

excel表格匯出,使用POI實現

******************************************************************************************

 

實現匯出步驟

——設定匯出excel模板,推薦使用03版xls格式,可以相容進階版本

 

——處理匯出資料List<Map<String, String>> 

private List<Map<String, String>> getData(){    List<Map<String, String>> data = new ArrayList<>();    Map<String, String> map = null;    for (int i = 0; i < 5; i++) {        map = new HashMap<String, String>();        map.put("listNo", i + "");        map.put("userName", "name" + i);        map.put("userAge", "" + (i + 20));        data.add(map);    }    return data;}

 

——擷取模板xls檔案,通過輸入資料流讀到HSSFWorkbook 對象中

private HSSFWorkbook workbookTemplate() {    File file = new File("f:/etom/pmms/src/test/resources/bdRoute.xls");    InputStream is = null;    HSSFWorkbook workbook = null;    try {        is = new FileInputStream(file);        workbook = new HSSFWorkbook(is);    } catch (IOException e) {        e.printStackTrace();    }finally {        if (null != is) {            try {                is.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }    return workbook;}

 

——通過頁簽名擷取頁簽

private HSSFSheet getSheet(HSSFWorkbook workbook) {    String sheetName = "使用者資訊";    HSSFSheet sheet = workbook.getSheet(sheetName);    if (null != sheet) {        return sheet;    }    return null;}

 

——擷取規則,如${userName}

private String getValue(HSSFCell cell){    int type = cell.getCellType();    switch (type) {        case Cell.CELL_TYPE_NUMERIC:            return Double.toString(cell.getNumericCellValue());        case Cell.CELL_TYPE_BOOLEAN:            return Boolean.toString(cell.getBooleanCellValue());        case Cell.CELL_TYPE_STRING:            return cell.getStringCellValue();        default:            return "";    }}

 

——設定規則,如${userName}

private void setCellRule(HSSFRow firstDataRow, HSSFRow newRow) {    HSSFCell cellInRule = null;    HSSFCell newCell = null;    for (int i = 0, cellNum = firstDataRow.getLastCellNum(); i < cellNum; i++) {        cellInRule = firstDataRow.getCell(i);        newCell = newRow.createCell(i);        HSSFCellStyle style = cellInRule.getCellStyle();        newCell.setCellStyle(style);        String rule = getValue(cellInRule);        newCell.setCellValue(rule);    }}

 

——設定頁簽模板,將內容行複製,行數與資料data的條數一致

// loop複製行的根據,rowCount複製多少行,上面中,複製行是從行號為4開始
private void setSheet(HSSFSheet sheet, int loop, int rowCount) {
HSSFRow newRow = null;
HSSFRow firstDataRow = sheet.getRow(loop - 1);
for (int i = loop, maxRow = loop + rowCount; i < maxRow - 1; i++) {
newRow = sheet.createRow(i);
setCellRule(firstDataRow, newRow);
}
}

 

——具體設定儲存格內容

private void setCellValue(HSSFRow row, Map<String, String> rowData) {    for (int i = 0, cellNum = row.getLastCellNum(); i < cellNum; i++) {        HSSFCell cell = row.getCell(i);        if (null == cell) {            continue;        }        String oldValue = getValue(cell);        Pattern pattern = Pattern.compile(patternRule);        Matcher matcher = pattern.matcher(oldValue);        if (matcher.find()) {            String key = matcher.group(1);            String value = rowData.getOrDefault(key, "");            cell.setCellValue(value);        }    }}

 

——設定行內容(通過設定儲存格內容)

// 設定內容,單元的範圍是從第loop行開始,到第loop+data.size()行結束
private void setValue(HSSFSheet sheet, int loop, List<Map<String, String>> data) {
HSSFRow row = null;
for (int i = loop - 1, rowNum = loop + data.size(), index = 0; i < rowNum - 1; i++) {
row = sheet.getRow(i);
setCellValue(row, data.get(index++));
}
}

 

——產生excel檔案,格式為xls

private void createExcel(HSSFWorkbook workbook,String targetPath){    File excelFile = new File(targetPath);    OutputStream os = null;    try {        os = new FileOutputStream(excelFile);        workbook.write(os);    } catch (IOException e) {        e.printStackTrace();    }finally {        if (null != os) {            try {                os.flush();                os.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

 

——測試

@Testpublic void test(){    List<Map<String, String>> data = getData(); // 擷取匯出的資料    String templatePath = "f:/etom/pmms/src/test/resources/user.xls"; // 模板的地址    HSSFWorkbook workbook = workbookTemplate(templatePath); // 將模板轉化為HSSFWorkbook對象    HSSFSheet sheet = getSheet(workbook); // 擷取模板頁簽    setSheet(sheet, 5, data.size()); // 設定頁簽    setValue(sheet, 5, data); // 設定儲存格內容    Long timeMillis = System.currentTimeMillis(); // 以目前時間命名匯出檔案名稱    String targetPath = String.format("f:/etom/pmms/src/test/resources/%s.xls", Long.toString(timeMillis)); // 匯出檔案xls地址    createExcel(workbook, targetPath); // 匯出檔案}

 

——結果展示

 

——合併儲存格

private void setRegion(HSSFSheet sheet){
int firstRow = 1; // 單元起始行
int lastRow = 2; // 儲存格終止行
int firstCol = 3; // 儲存格起始列
int lastCol = 4; // 儲存格終止列
CellRangeAddress cellRangeAddress = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
sheet.addMergedRegion(cellRangeAddress);
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.