Вставьте новые строки в электронную таблицу Apache POI на основе содержимого ячейки - PullRequest
0 голосов
/ 30 сентября 2019

ПРИМЕЧАНИЕ: я искал везде, и это не повторяющийся вопрос.

Я пытаюсь создать / вставить фиксированное количество «новых» строк в электронную таблицу, используяApache POI (poi-4.1.0) и Java на основе содержимого ячейки в той же строке - см. Диаграмму ниже («|» обозначает разрыв столбца):

1 Foo |1001, 1002, 1003 | Да
2 Бар |1010 | Да
3 Slf |2500, 1500, 5200 | Да

По сути, произойдет следующее: я вставлю две новые строки между строками 1 и 2 и снова после строки 3, дублируя все данные из строки источника, за исключением того, что вместоимея три значения (или сколько их может быть) во втором столбце, будет только одно - см. диаграмму ниже («|» обозначает разрыв столбца):

1 Foo |1001 | Да
2 Foo1 |1002 | Да
3 Foo2 |1003 | Да
4 Бар |1001 | Да
5 Slf |2500 | Да
6 Slf1 |1500 | Да
7 Slf2 |5200 | Да

Этот процесс будет повторяться, только для ячеек с несколькими значениями, пока все строки в файле не будут прочитаны и обработаны. Я должен отметить, что новые строки будут добавлены в тот же файл.

Вот что у меня есть для кода (я использовал код на этой странице в качестве шаблона и попытался обновить егодля соответствия текущей версии POI, которую я использую):

public class XLSXFileAdd {
private static final String prpfile = "src/main/resources/fileinfo/directories.properties";

public static void main(String[] args) throws Exception{      
    File infile = new File(XLSXFileAdd.getCIFile()); //Gets the fully-qualified path to the input file.
    XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(infile));
    XSSFSheet sheet = workbook.getSheet("Sheet1"); //Opens the XLSX document at the specified worksheet.
    String msNum; //The string that will hold the contents of the cell with multiple values.
    XLSXFileAdd xfa = new XLSXFileAdd();
    for(int i = 1; i <= sheet.getLastRowNum(); i++){
        Row row = sheet.getRow(i);            
        msNum = String.valueOf(row.getCell(2));
        if(i == 2 && msNum.length() > 4){ //If the current column in the row is equal to the cell that could contain multiple values and the number of values in the cell are greater than 1 (length is greater than 4 for multiple values)
            xfa.copyRows(workbook,sheet,i, i);
        }else{
            //Read and parse the file normally (the method used here works without issue so I have not copied it to reduce clutter and confusion).
        }               
    }
}

private static String getCIFile(){
    File propfile = new File(prpfile);
    Properties properties = new Properties();
    try{
        FileInputStream fis = new FileInputStream(propfile);
        properties.load(fis);
    }catch(IOException ex){
        Logger.getLogger(XLSXFileAdd.class.getName()).log(Level.SEVERE, null, ex);
}
    String filename = (String)properties.get("xlsx.input.custdata");
    return filename;
}

private void copyRows(XSSFWorkbook workbook,XSSFSheet worksheet,int sourceRowNum, int destinationRowNum){
    //Get source & destination row
    Row newRow = worksheet.getRow(destinationRowNum);
    Row sourceRow = worksheet.getRow(sourceRowNum);

    //Check if the row will be overwritten; if the row is populated, push down all rows by one and create a new row
    if(newRow != null){
        worksheet.shiftRows(destinationRowNum,worksheet.getLastRowNum(), 1);
    }else{
        newRow = worksheet.createRow(destinationRowNum);
    }

    //Loop through source columns to add to new row.
    for(int i = 0; i < sourceRow.getLastCellNum(); i++){
        Cell oldCell = sourceRow.getCell(i);
        Cell newCell = newRow.createCell(i);

        //If the old is not populated (null), jump to next cell
        if(oldCell == null){
            newCell = null;
            continue;
        }

        //Set newly created cells to the style of the source cell
        newCell.setCellStyle(oldCell.getCellStyle());

        //Set the cell data type
        newCell.setCellType(oldCell.getCellType());

        //Set the value of the cell
        switch(oldCell.getCellType()){
            case _NONE:
                newCell.setCellValue(oldCell.getStringCellValue());
                break;
            case BLANK:
                break;
            case BOOLEAN:
                newCell.setCellValue(oldCell.getBooleanCellValue());
                break;
            case ERROR:
                newCell.setCellErrorValue(oldCell.getErrorCellValue());
                break;
            case FORMULA:
                newCell.setCellFormula(oldCell.getCellFormula());
                break;
            case NUMERIC:
                newCell.setCellValue(oldCell.getNumericCellValue());
                break;
            case STRING:
                newCell.setCellValue(oldCell.getRichStringCellValue());
                break;       
        }           
    }

    //Check for merged regions and copy said regions to new row.
    for(int i = 0; i <worksheet.getNumMergedRegions(); i++){
        CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
        if(cellRangeAddress.getFirstRow() == sourceRow.getRowNum()){
            CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),
                    (newRow.getRowNum()+(cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow()
                            )),cellRangeAddress.getFirstColumn(),cellRangeAddress.getLastColumn());
            worksheet.addMergedRegion(newCellRangeAddress);
        }
    }        
}

Когда я запускаю код, он работает нормально и говорит, что он успешно завершен, однако, когда я пытаюсь открыть измененный файл, он жалуется на поврежденныйданные и удаляет все, кроме двух строк из файла (если я позволю MS Excel попытаться восстановить его). Я также попытался перенаправить вывод в другой файл, но результаты те же - он повреждает данные и показывает только две строки с пустой строкой между ними.

Так что мой вопрос (ы) является / являютсяэто: 1) Есть ли лучший способ сделать то, что я хочу сделать? 2) Если нет [лучшего способа], что я делаю неправильно, что приводит к повреждению всех данных, которые я пытаюсь записать.

1 Ответ

0 голосов
/ 04 октября 2019

Так что мне удалось решить мою проблему. Вместо того, чтобы пытаться добавить под исходную строку, я решил добавить строку в конец файла, что значительно упростило логику. Вот код, который я создал, чтобы решить проблему:

public void addAddtlRows(Sheet sheet,Workbook workbook,DataFormatter formatter, ImportDataFormatter fmt, File file){

     //Loads and parses the regular expression into memory and creates a new StringBuilder() instance.
    final Pattern p = Pattern.compile(regex);
    StringBuilder sb = new StringBuilder();

    //Create the array which holds all the entries from a cell that contains multiple entries
    String[] sysNumber;

    //The number of the last row in the sheet.
    int lastRow = sheet.getLastRowNum();

    //Instantiates an integer that will be assigned the length of the array later
    int arrayLength;

    //Loops through the each row in the sheet 
    for(int r = 1; r < lastRow; r++){
        Row row = sheet.getRow(r);
        String cellData = formatter.formatCellValue(row.getCell(2));
        String active = formatter.formatCellValue(row.getCell(4));


        if((cellData.length() > 4) && (active.equals("Yes"))){

             /** Checks whether or not we are on the cell containing the
             * numbers and whether or not they are currently active.
             * If we are, get values for all cells in the row
             */
            String an = formatter.formatCellValue(row.getCell(0));
            String cn = formatter.formatCellValue(row.getCell(1));
            String ca = formatter.formatCellValue(row.getCell(3));
            String es = formatter.formatCellValue(row.getCell(4));
            String i10 = formatter.formatCellValue(row.getCell(5));
            String i9 = formatter.formatCellValue(row.getCell(6));
            String ia = formatter.formatCellValue(row.getCell(7));
            String rp = formatter.formatCellValue(row.getCell(8));

            /**
             * Checks the contents of the cell for more than one entry
             * If the cell contains more than one number, process
             * the data accordingly
             */

            fmt.setSysNum(cellData);
            String[] sys = String.valueOf(fmt.getSysNum()).split(",");

            /**
             * Assign the length value of the 'sysNumber' array to
             * the integer 'arrayLength'
             */
            arrayLength = sys.length;

            /**
             * Loop through each entry in the string array, creating
             * a new row on each iteration and pasting the data from
             * the old cells to the new ones
             */
            for(int n = 0; n < arrayLength; n++){
                Row nRow = sheet.createRow(sheet.getPhysicalNumberOfRows());
                nRow.createCell(0).setCellValue(an);
                nRow.createCell(1).setCellValue(cn);
                nRow.createCell(2).setCellValue(sys[n]);
                nRow.createCell(3).setCellValue(ca);
                nRow.createCell(4).setCellValue(es);
                nRow.createCell(5).setCellValue(i10);
                nRow.createCell(6).setCellValue(i9);
                nRow.createCell(7).setCellValue(ia);
                nRow.createCell(8).setCellValue(rp);

            } 
        }              
    }

    //Writes the newly added contents of the worksheet to the workbook.
    try {
    workbook.write(new FileOutputStream(file));
    } catch (FileNotFoundException ex) {
    Logger.getLogger(MapMultipleSNToDBFields.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
    Logger.getLogger(MapMultipleSNToDBFields.class.getName()).log(Level.SEVERE, null, ex);
    }
}
...