创建具有样式的Excel
依赖
<dependencies> <!-- poi依赖--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.1</version> </dependency> <!-- poi对于excel 2007的支持依赖--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.1</version> </dependency> <!-- poi对于excel 2007的支持依赖--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>4.0.1</version> </dependency> </dependencies>
java 代码
package com.zhao; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.time.LocalDate; public class creatPoiFile { public static void main(String[] args) { // HSSFWorkbook 2003 版 XSSFWorkbook 2007版 //1.创建workbook工作簿 Workbook wb = new XSSFWorkbook(); //2.创建表单Sheet Sheet sheet = wb.createSheet("test"); //3.创建行对象,从0开始 ,创建第三行 Row row = sheet.createRow(2); //4.创建单元格,从0开始 ,第2个单元格 Cell cell = row.createCell(1); //5.单元格写入数据 cell.setCellValue(LocalDate.now() + " :poi 学习"); //创建单元格样式对象 CellStyle cellStyle = wb.createCellStyle(); //设置边框 cellStyle.setBorderBottom(BorderStyle.THIN);//下边框 cellStyle.setBorderTop(BorderStyle.THIN);//上边框 //设置字体 Font font = wb.createFont();//创建字体对象 font.setFontName("华文行楷");//设置字体 font.setFontHeightInPoints((short) 28);//设置字号 cellStyle.setFont(font); //设置宽高 sheet.setColumnWidth(1, 31 * 256);//设置第2列的宽度是31个字符宽度 ,这个写进去的时字符宽度所以要乘以256 row.setHeightInPoints(50);//设置行的高度是50个点 //设置居中显示 cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中 //设置单元格样式 cell.setCellStyle(cellStyle); //合并单元格 // CellRangeAddress region =new CellRangeAddress(0, 3, 0, 2); // sheet.addMergedRegion(region); //3.文件流 FileOutputStream fos = null; try { fos = new FileOutputStream("D:\\projectCode\\poiUtils\\test.xlsx"); //4.写入文件 wb.write(fos); } catch (Exception e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }

浙公网安备 33010602011771号