0
点赞
收藏
分享

微信扫一扫

java对指定的excel续写入数据

/**
 * 向已知表中插入数据,累计追加
 * 写入前先判断表是否存在,表中是否有数据
 *
 * @param dateList list实体类对象
 * @param filePath excel的路径 D:\\123.xls
 * @throws Exception
 */
public static void inserSheetData(List<excelDate> dateList, String filePath) throws Exception {
    // String filePath = "D:\\123.xls";
    FileInputStream fs = new FileInputStream(filePath);

    //使用POI提供的方法得到excel的信息
    POIFSFileSystem fileSystem = new POIFSFileSystem(fs);
    HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fileSystem);
    //获取到工作表,因为一个excel可能有多个工作表
    HSSFSheet InsertSheet = hssfWorkbook.getSheetAt(0);
    //获取第一行(excel中的行默认从0开始,所以这就是为什么,一个excel必须有字段列头),即,字段列头,便于赋值
    HSSFRow row = ((HSSFSheet) InsertSheet).getRow(0);
    //分别得到最后一行的行号,和一条记录的最后一个单元格
    System.out.println("最后一行的行 " + InsertSheet.getLastRowNum());
    //向文件中写入数据
    FileOutputStream out = new FileOutputStream(filePath);

    //指定行
    // int lastRowNum = 20;
    for (excelDate excelDate : dateList) {
        // 获取存在数据最大的行+1
        int lastRowNum = InsertSheet.getLastRowNum() + 1;
        //在指定行后追加数据
        row = InsertSheet.createRow(lastRowNum);
        //设置第一个(从0开始)单元格的数据
        row.createCell(0).setCellValue(excelDate.getName());
        row.createCell(1).setCellValue(excelDate.getAge());
        row.createCell(2).setCellValue(excelDate.getPhone());
    }
    out.flush();
    hssfWorkbook.write(out);
    out.close();
}

需要的jar

<!--使用POI读取文件-->
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.8</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.8</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>ooxml-schemas</artifactId>
  <version>1.4</version>
</dependency>

java对指定的excel续写入数据_apache

举报

相关推荐

0 条评论