使用Apache POI操作Excel文件---在已有的Excel文件中插入一行新的数据

package com.csair.oas.utils.test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class ExcelWriter {
    private static final Log log = LogFactory.getLog(ExcelWriter.class);

    private static final String FTP_BASE_PATH = "D:\\code\\oasdata\\相关航线导入\\源数据导出\\bak\\";
    private static final String FILE_NAME_REDEX_XLS = "^相关航线数据-\\d{6}\\.xls$";
    private static final String FILE_NAME_REDEX_XLSX = "^相关航线数据-\\d{6}\\.xlsx$";
    private static final ArrayList<String> scanFiles = new ArrayList<String>();//文件路径
    private static final ArrayList<String> dirctorys = new ArrayList<String>();//文件夹路径

    public static void main(String[] args) {
        List<String> fileNames=scanFiles(FTP_BASE_PATH);

        String sheetName="Sheet";
        int insertStartPointer=0;
        ExcelWriter t=new ExcelWriter();
        //用for循环添加三行数据
        for(int i=0;i<3;i++) {
            for(String excelPath:fileNames){
                t.insertRows(sheetName,insertStartPointer,excelPath);
            }

        }

    }

    /**
     * 扫描文件夹的所有文件
     * @return
     */
    public static List<String> scanFiles(String folderPath){

        File directory = new File(folderPath);
        if(!directory.isDirectory()){
            //throw new ScanFilesException('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
            log.error('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
        }
        if(directory.isDirectory()){
            File [] filelist = directory.listFiles();
            for(int i = 0; i < filelist.length; i ++){
                /**如果当前是文件夹,进入递归扫描文件夹**/
                if(filelist[i].isDirectory()){
                    dirctorys.add(filelist[i].getAbsolutePath());
                    /**递归扫描下面的文件夹**/
                    scanFiles(filelist[i].getAbsolutePath());
                }
                /**非文件夹**/
                else{
                    //添加符合的文件
                     if(Pattern.matches(FILE_NAME_REDEX_XLS, filelist[i].getName().replaceAll(" ",""))||Pattern.matches(FILE_NAME_REDEX_XLSX, filelist[i].getName().replaceAll(" ",""))){
                         scanFiles.add(filelist[i].getAbsolutePath());
                     }
                }
            }
        }
        return scanFiles;
    }
    /**
     * 在已有的Excel文件中插入一行新的数据的入口方法
     */
    public void insertRows(String sheetName,int insertStartPointer,String excelPath) {
        XSSFWorkbook wb = returnWorkBookGivenFileHandle(excelPath);
        XSSFSheet sheet1 = wb.getSheet(sheetName);
        XSSFRow row = createRow(sheet1, insertStartPointer);
        createCell(row);
        saveExcel(wb,excelPath);

    }

    /**
     * 找到需要插入的行数,并新建一个POI的row对象
     * @param sheet
     * @param rowIndex
     * @return
     */
    private XSSFRow createRow(XSSFSheet sheet, Integer rowIndex) {
        XSSFRow row = null;
        if (sheet.getRow(rowIndex) != null) {
            int lastRowNo = sheet.getLastRowNum();
            sheet.shiftRows(rowIndex, lastRowNo, 1);
        }
        row = sheet.createRow(rowIndex);
        return row;
    }

    /**
     * 创建要出入的行中单元格
     * @param row
     * @return
     */
    private XSSFCell createCell(XSSFRow row) {
        XSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("string");
        row.createCell(1).setCellValue("string");
        row.createCell(2).setCellValue("This is a string cell");
        return cell;
    }


    /**
     * 保存工作薄
     * @param wb
     */
    private void saveExcel(XSSFWorkbook wb,String excelPath) {
        FileOutputStream fileOut;
        try {
            fileOut = new FileOutputStream(excelPath);
            wb.write(fileOut);
            fileOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 得到一个已有的工作薄的POI对象
     * @return
     */
    private XSSFWorkbook returnWorkBookGivenFileHandle(String excelPath) {
        XSSFWorkbook wb = null;
        FileInputStream fis = null;
        File f = new File(excelPath);
        try {
            if (f != null) {
                fis = new FileInputStream(f);
                wb = new XSSFWorkbook(fis);
            }
        } catch (Exception e) {
            return null;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return wb;
    }
}

https://www.cnblogs.com/sunhaoyu/p/7672630.html

posted @ 2020-12-30 10:11  一叶知秋。  阅读(1139)  评论(0编辑  收藏  举报