用JAVA创建excel文件并写入数据

建立文件并创建sheet页:

private void createWorkbook() {
        this.workbook = new HSSFWorkbook();
        this.workbook.createSheet();
        this.workbook.setSheetName(0, this.getSheetName(), (short) 1);
    }

在sheet页中写入标题:

private void writeHead() {
        HSSFSheet sheet = this.workbook.getSheetAt(0);
        HSSFRow row = null;
        HSSFCell cell = null;

        HSSFCellStyle style = this.workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中
       
        //表头始终是第一行
        row = sheet.createRow(0);
        List head = this.getWorkbookHead();
        for (short col = 0; col < head.size(); col++) {
            cell = row.createCell(col);
            cell.setEncoding(HSSFCell.ENCODING_UTF_16);// 这里是设置编码保证中文正常显示
            cell.setCellValue((String) head.get(col));
            cell.setCellStyle(style);
        }
    }

在sheet页中写入数据:

HSSFSheet sheet = this.workbook.getSheetAt(0);
        HSSFRow row = null;
        HSSFCell cell = null;
       
        //数据从第二行开始
        Iterator data = this.getData("").iterator();
        for (int rowNo = 1; data.hasNext(); rowNo++) {
            row = sheet.createRow(rowNo);
           
            List cellData = this.flatObjectForShow(data.next());
            for (short col = 0; col < cellData.size(); col++) {
                cell = row.createCell(col);
                cell.setEncoding(HSSFCell.ENCODING_UTF_16);// 这里是设置编码保证中文正常显示
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue((String) cellData.get(col));
            }
        }
    }

 

你可能感兴趣的:(java,Excel)