Update existing excel file in java using Fastexcel

498 Views Asked by At

I am new in fastexcel library in java. I want to update my existing excel file using Fastexcel library. but when I try to do it at that time It will clean all the data and create new File.

I am following below example.

https://howtodoinjava.com/java/library/read-write-large-excel-files/

Need to update Existing excel file.

1

There are 1 best solutions below

0
On

FastExcel library seems primarily designed for reading and writing Excel files in a fast and memory-efficient way and does not support updating an existing Excel file directly, so the "update" function will be achieved via reading all source file and writing a new file with new information.

Somthing like that:

package org.example;

import org.dhatim.fastexcel.Workbook;
import org.dhatim.fastexcel.Worksheet;
import org.dhatim.fastexcel.reader.Cell;
import org.dhatim.fastexcel.reader.ReadableWorkbook;
import org.dhatim.fastexcel.reader.Row;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        try (InputStream is = Files.newInputStream(Paths.get("path/to/your/excel/file.xlsx"))) {
            ReadableWorkbook reader = new ReadableWorkbook(is);
            try (OutputStream os = Files.newOutputStream(Paths.get("path/to/your/new/excel/file.xlsx"))) {
                Workbook writer = new Workbook(os, "MyApplication", "1.0");
                reader.getSheets().forEach(sheet -> {
                    Worksheet worksheet = writer.newWorksheet(sheet.getName());
                    Stream<Row> rowStream = null;
                    try {
                        rowStream = sheet.openStream();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    rowStream.forEach(row -> {
                        int i = 0;
                        for (Cell cell : row) {
                            String text = cell.getText();
                            // Uppercase first row values for each sheets
                            if (row.getRowNum() == 1) {
                                text = text.toUpperCase();
                            }
                            worksheet.value(row.getRowNum() - 1, i++, text);
                        }
                    });
                });
                writer.finish();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

here a full example on github