Search code examples
jmeterjmeter-pluginsbeanshell

How to write data at particular cell in excel/csv file in jmeter using beanshell?


I am trying to write the data in excel or CSV file using beanshell. But i am able to write the data in excel sheet but unable to write the data at particular cell in CSV file.

Below is the code.

var response = prev.getResponseDataAsString(); 
f = new FileOutputStream("C:/Users/adityak/Desktop/K/app.csv", true);
p = new PrintStream(f);
this.interpreter.setOut(p);
print(response);
f.close();

Solution

    1. CSV file doesn't have "cells", it is plain text file with delimiters, mostly commas as CSV stands for comma-separated values
    2. Since JMeter 3.1 it is recommended to use Groovy for scripting
    3. Assuming all above:

    For example if you have file like:

    1,2,3
    4,5,6
    7,8,9
    

    and want to replace 5 with hello the relevant Groovy code would be something like:

    def csvFile = new File('/home/dtikhanski/Desktop/test.csv')
    def lines = csvFile.readLines()
    
    
    def secondLine = lines.get(1)
    def entries = secondLine.split(",")
    entries[1] = 'hello'
    secondLine = entries.join(',')
    lines.set(1, secondLine)
    
    csvFile.withWriter{ out ->
        lines.each {out.println it}
    }
    

    Demo:

    JMeter Groovy Replace CSV