@author YHC
工作薄中不同类型的单元格
Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("new sheet"); Row row = sheet.createRow(2); row.createCell(0).setCellValue(1.1);//浮点 row.createCell(1).setCellValue(new Date());//日期 row.createCell(2).setCellValue(Calendar.getInstance());//日期 row.createCell(3).setCellValue("a string");//字符串 row.createCell(4).setCellValue(true);//Boolean row.createCell(5).setCellType(Cell.CELL_TYPE_ERROR);//错误 // 写入文件 FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();
运行结果:
展示各种对其选项
public static void main(String[] args) throws Exception { Workbook wb = new XSSFWorkbook(); //或者创建 HSSFWorkbook();对象 Sheet sheet = wb.createSheet();//创建工作薄 Row row = sheet.createRow((short) 2);//创建行 row.setHeightInPoints(30);//设置高度Point像素单位设置高度 createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM); createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM); createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER); createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER); createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY); createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP); createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP); //写入文件 FileOutputStream fileOut = new FileOutputStream("xssf-align.xls"); wb.write(fileOut); fileOut.close(); } /** * 创建一个单元格,并以一种特定的样式对齐 * * @param wb Workbook对象 * @param row 创建单元格的行对象 * @param column 列的编号,单元格创建位置 * @param halign 单元格中的水平对齐方式. * @param valign 单元格中的垂直对齐方式 */ private static void createCell(Workbook wb, Row row, short column, short halign, short valign) { Cell cell = row.createCell(column);//创建Cell cell.setCellValue("Align It");//设置值 CellStyle cellStyle = wb.createCellStyle();//创建样式 cellStyle.setAlignment(halign);//设置水平对齐方式 cellStyle.setVerticalAlignment(valign);//设置垂直对齐方式 cell.setCellStyle(cellStyle);//给单元格添加样式 }
运行结果: