zoukankan      html  css  js  c++  java
  • POI3.16导出Excel使用

    创建Excel文档工作簿:

    xlsx版本

    // 支持数据量可超过100万行
    XSSFWorkbook workBook = new XSSFWorkbook();
    

    xls版本

    // 由于版本问题,行数不能超过65536
    HSSFWorkbook workBook = new HSSFWorkbook();
    

    下文的单元格相关的代码均以xlsx版本为例,如需以xls版本导出 一般将前缀为XSSF的改为HSSF即可

    生成文件

    FileOutputStream output=new FileOutputStream("/cluster/excel/helloWorld.xlsx");
    workBook.write(output);
    output.flush();
    workBook.close();
    

    // 建立新的sheet对象(excel的表单)
    XSSFSheet sheet = workBook.createSheet("sheet1");
    

    // 设置行高
    XSSFRow row = sheet.createRow(3);
    // 生成后的行高大概为57,0.75为转换率
    row.setHeightInPoints((float) (57 * 0.75));
    

    // 设置列宽,生成后的列宽大概为12,256为转换率
    sheet.setColumnWidth(0, 12*256);
    // 设置自适应列宽(中文自适应不准确)
    sheet.autoSizeColumn(0);
    

    单元格:

    创建单元格:

    // 0为第一列,1为第二列,以此类推
    XSSFCell cell = row.createCell(0);
    // 设置值
    cell.setCellValue("Hello World!");
    

    样式:

    // 水平居中
    cellStyle.setAlignment(HorizontalAlignment.CENTER);
    // 垂直居中
    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    // 字体
    XSSFFont font = workBook.createFont();
    // 加粗
    font.setBold(true);
    // 斜体
    font.setItalic(true);
    // 字体样式
    font.setFontName("宋体");
    // 文字大小
    font.setFontHeightInPoints((short)18);
    // 单元格样式
    XSSFCellStyle cellStyle = workBook.createCellStyle();
    // 自动换行
    cellStyle.setWrapText(true);
    // 设置单元格字体样式
    cellStyle.setFont(font);
    // 将以上编辑的样式设置到单元格中
    cell.setCellStyle(cellStyle);
    

    特殊样式:

    // 如果需要在一个单元格中换行(需设置自动换行)或者设置多种不同样式则需要使用到富文本
    XSSFRichTextString richTextStr = new XSSFRichTextString("行1
    行2
    行3");
    // 将值设置到单元格中
    cell.setCellValue(richTextStr);
    

    合并单元格:

    // 需要传入CellRangeAddress类型的变量
    int org.apache.poi.xssf.usermodel.XSSFSheet.addMergedRegion(CellRangeAddress region)
    // CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
    org.apache.poi.ss.util.CellRangeAddress.CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol)
    // 示例:合并第一列到第12列
    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 12));
  • 相关阅读:
    AtCoder Grand Contest 015 题解
    AtCoder Grand Contest 014 题解
    AtCoder Grand Contest 013 题解
    AtCoder Grand Contest 012 题解
    AtCoder Grand Contest 011 题解
    AtCoder Grand Contest 010 题解
    AtCoder Grand Contest 009 题解
    NOIP2017 Day2 题解
    博客园主题备份
    多项式全家桶
  • 原文地址:https://www.cnblogs.com/runningRookie/p/11108781.html
Copyright © 2011-2022 走看看