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>