欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

poi 博客分类: java  

程序员文章站 2024-03-14 12:37:34
...

 

 Workbook workbook  = new XSSFWorkbook();

    Sheet sheet = workbook.createSheet();

   

    sheet.setColumnWidth(0, 4500);

 

 

//设置为文本格式

Font font1 = workbook.createFont();

font1.setFontHeightInPoints((short) 14);

    CellStyle cellStyle  = workbook.createCellStyle();

    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中  

    cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

    cellStyle.setFont(font1);

 

 

Row row0 = sheet.createRow(0);

    row0.setRowStyle(cellStyle);

    Row row3 = sheet.createRow(2);

 

//合并单元格

sheet.addMergedRegion( new CellRangeAddress(0, 2, 2, 2) );

 

OutputStream out = response.getOutputStream();

workbook.write(response.getOutputStream());

out.close();// 关闭文件输出流

 

 

public static String formatCell(Cell cell){

    String ret;

switch (cell.getCellType()) {

case Cell.CELL_TYPE_STRING:

ret = cell.getStringCellValue();

break;

case Cell.CELL_TYPE_FORMULA:

Workbook wb = cell.getSheet().getWorkbook();

CreationHelper crateHelper = wb.getCreationHelper();

FormulaEvaluator evaluator = crateHelper.createFormulaEvaluator();

ret = formatCell(evaluator.evaluateInCell(cell));

break;

case Cell.CELL_TYPE_NUMERIC:

if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式  

                SimpleDateFormat sdf = null;  

                if (cell.getCellStyle().getDataFormat() == HSSFDataFormat  

                        .getBuiltinFormat("h:mm")) {  

                    sdf = new SimpleDateFormat("HH:mm");  

                 } else {// 日期  

                     sdf = new SimpleDateFormat("yyyy-MM-dd");  

                 }  

                 Date date = cell.getDateCellValue();  

                 ret = sdf.format(date);  

             } else if (cell.getCellStyle().getDataFormat() == 58) {  

                 // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)  

                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  

                 double value = cell.getNumericCellValue();  

                 Date date = org.apache.poi.ss.usermodel.DateUtil  

                         .getJavaDate(value);  

                 ret = sdf.format(date);  

             } else {  

                 ret = NumberToTextConverter.toText(cell.getNumericCellValue());

             } 

break;

case Cell.CELL_TYPE_BLANK:

ret = "";

break;

case Cell.CELL_TYPE_BOOLEAN:

ret = String.valueOf(cell.getBooleanCellValue());

break;

case Cell.CELL_TYPE_ERROR:

ret = null;

break;

default:

ret = null;

}

return ret; //有必要自行trim

    }