Spring之POI从入门到入门……

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Martind/article/details/82149968

环境配置

首先要再maven的 pom.xml 中导入 poi,poi-ooxml , poi-ooxml-schemas 这三个依赖

      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.9</version>
    </dependency>

入门示例

public class LearnPOI {
    public static void main(String[] args) throws IOException {
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int cnt = 0;
        SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet("0");
        for(int i=0; i<20000;i++){
            if(i%10000==0 && i!=0){
               sheet = (SXSSFSheet) workbook.createSheet(String.valueOf(i));
               cnt = 0;
            }
            SXSSFRow row = (SXSSFRow) sheet.createRow(cnt);
            row.createCell(0).setCellValue(df.format(new Date()));
            cnt++;
        }
        FileOutputStream fileOutputStream = new FileOutputStream("Martin.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
    }
}

创建新的excel文件
SXSSFWorkbook workbook = new SXSSFWorkbook();
创建新的标签页
SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet("新的标签页");
设置行宽度为自适应
sheet.autoSizeColumn(5);
创建新的一行
SXSSFRow row = (SXSSFRow) sheet.createRow(0);
创建样式
XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
自定义单元格背景颜色,也可使用预定颜色
style.setFillForegroundColor(new XSSFColor(new java.awt.Color(169, 208, 142)));
style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
设置样式为居中
style.setAlignment(CellStyle.ALIGN_CENTER);
写入文件
FileOutputStream fileOutputStream = new FileOutputStream("D:\\leave.xlsx");
workbook.write(fileOutputStream);
fileOutputStream.close();

设置制定列宽度
sheet.setColumnWidth(2,50*256);

参考1

猜你喜欢

转载自blog.csdn.net/Martind/article/details/82149968
今日推荐