Java Snippet node

I have problem i want to create 3 new rows in a specific place in excel :
i used this : // Your custom imports:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

// system variables
public class JSnippet extends AbstractJSnippet {

// Your custom variables:

// expression start
public void snippet() throws TypeException, ColumnException, Abort {
// Enter your code here:
// Define file paths and row insertion parameters
String inputFilePath = “Sign in to your account”; // Update this path
String outputFilePath = “Sign in to your account”; // Update this path
int insertRowIndex = 5; // Row index where new rows will be inserted
int numberOfRows = 3; // Number of new rows to insert

    // Use a simple list of strings to store the lines
    java.util.List<String> lines = new java.util.ArrayList<String>();

    // Read the original CSV file
    try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath))) {
        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Insert new rows at the specified index
    for (int i = 0; i < numberOfRows; i++) {
        lines.add(insertRowIndex + i, "New Data " + (i + 1) + ",,,"); // Adjust columns as needed
    }

    // Write the modified data back to a new CSV file
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
        for (String line : lines) {
            writer.write(line);
            writer.newLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

// expression end
Wrote this but the problem is that the node requires input and output columns what should i do

Hi @Haya_Tawakol ,

Welcome to the KNIME forum.

It appears that you are actually modifying a csv file rather than an excel file, but regardless, I understand that you are wanting to execute this within the “java snippet” environment but are not really wanting to perform this as part of “table processing” with input and output columns, which is what the java snippet node is designed for.

Instead of “Java Snippet” you could try writing the code within the “Java Edit Variable” node. It works the same as Java Snippet but doesn’t require any table data to be present.

image

You could alternatively do this using standard KNIME nodes without needing to write any java, such as:

hope that helps

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.