package poiexcel; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * @ClassName MyDc * @Description TODO * @Author as * @Date 2021/11/26 11:03 */ public class MyDc { public static void main(String[] args) { //1.创建excel文档对象 HSSFWorkbook workbook = new HSSFWorkbook(); //2.获取excel表单对象 HSSFSheet sheet = workbook.createSheet("表数据demo"); //3.获取标题行(第1行)对象 HSSFRow row = sheet.createRow(0); //4.创建标题行中列(第1列)对象 HSSFCell cell = row.createCell(0); //设置标题名称 cell.setCellValue("标题demo"); //5.合并单元格,将坐标(0,0)单元格到(5,5)单元格合并(默认行数和列数都是从0开始的) /* 参数1:开始行号 参数2:结束行号 参数3:开始列号 参数4:终止列号 */ CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 1); sheet.addMergedRegion(cellRangeAddress); //6.填入列名 /* 1)获取第一行对象 2)获取各个列对象 3)设置各个列的内容 */ HSSFRow row1 = sheet.createRow(1); HSSFCell r1c1 = row1.createCell(0); r1c1.setCellValue("姓名"); HSSFCell r1c2 = row1.createCell(1); r1c2.setCellValue("学号"); //7.填入数据 HSSFRow row2 = sheet.createRow(2); HSSFCell r2c1 = row2.createCell(0); r2c1.setCellValue("吴照生"); HSSFCell r2c2 = row2.createCell(1); r2c2.setCellValue("2350170219"); //8.导出数据到excel FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream("E:\\demo.xls"); workbook.write(fileOutputStream); fileOutputStream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(fileOutputStream != null){ try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.17</version> </dependency>