ExtractData

mail@pastecode.io avatar
unknown
java
8 months ago
2.6 kB
16
Indexable
Never
package org.example;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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

public class ExcelFileProcessor {
    public static void main(String[] args) {
        try {
            // Get the current directory
            File currentDirectory = new File(".");
            File[] files = currentDirectory.listFiles();

            if (files != null) {
                for (File file : files) {
                    if (file.isFile() && file.getName().endsWith(".xlsx")) {
                        processExcelFile(file);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void processExcelFile(File inputFile) throws IOException {
        FileInputStream fis = new FileInputStream(inputFile);
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0); // Assuming you want to process the first sheet

        List<String> addresses = new ArrayList<>();
        List<String> contactData = new ArrayList<>();

        final int addressRowIndex = 2;
        final int contactRowIndex = 4;
        final int columnIndex = 1;

        Row addressRow = sheet.getRow(addressRowIndex);
        Row contactRow = sheet.getRow(contactRowIndex);

        if (addressRow != null && contactRow != null) {
            Cell addressDataCell = addressRow.getCell(columnIndex);
            Cell contactDataCell = contactRow.getCell(columnIndex);
            if (addressDataCell != null && contactDataCell != null) {
                addresses.add(addressDataCell.getStringCellValue());
                contactData.add(contactDataCell.getStringCellValue());
            }
        }

        // Create a new Excel file to store the result
        Workbook resultWorkbook = new XSSFWorkbook();
        Sheet resultSheet = resultWorkbook.createSheet("Result");

        // Write the contact data and matching address to the new Excel file
        for (int i = 0; i < addresses.size(); i++) {
            Row row = resultSheet.createRow(i);
            row.createCell(0).setCellValue(contactData.get(i));
            row.createCell(1).setCellValue(addresses.get(i));
        }

        // Save the result to a new file
        String outputFileName = "result_" + inputFile.getName();
        FileOutputStream fos = new FileOutputStream(outputFileName);
        resultWorkbook.write(fos);

        // Close all streams
        fis.close();
        fos.close();
        workbook.close();
        resultWorkbook.close();
    }
}