How to read column a1 from an Excel sheet and perform string matching to define variables in a Java program -
i need read 1 fixed column of excel sheet , column need find out variables , load them java program.
for example need read column a1 contains following data: "what /@v1@/% of /@v2@/?"
/@v1@/ , /@v2@/ variables. java program needs detect these variables , insert random values them. have done following:
import java.io.fileinputstream; import java.util.arraylist; import java.util.list; import org.apache.poi.hssf.usermodel.hssfsheet; import org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.poi.poifs.filesystem.poifsfilesystem; import org.apache.poi.ss.usermodel.cell; import org.apache.poi.ss.usermodel.row; public class acgs { public static void main(string[] args) throws exception { //test file located in project path fileinputstream filein = new fileinputstream("c://users/admin/desktop/content.xls"); //read file poifsfilesystem fs = new poifsfilesystem(filein); hssfworkbook filename = new hssfworkbook(fs); //open sheet 0 first sheet of worksheet hssfsheet sheet = filename.getsheetat(0); //we search column index containing string "your column name" in row 0 (which first row of worksheet string columnwanted = "v4"; integer columnno = null; //output not null values list list<cell> cells = new arraylist<cell>(); row firstrow = sheet.getrow(0); for(cell cell:firstrow){ if (cell.getstringcellvalue().equals(columnwanted)){ columnno = cell.getcolumnindex(); } } if (columnno != null){ (row row : sheet) { cell c = row.getcell(columnno); if (c == null || c.getcelltype() == cell.cell_type_blank) { // nothing in cell in row, skip } else { cells.add(c); } } }else{ system.out.println("could not find column " + columnwanted + " in first row of " + filein.tostring()); } }
}
could tell me how can proceed further?
it sounds can use excel template processing solution. 2 i'm aware of jxls , jett (disclaimer: wrote jett , maintain it).
the libraries similar, in both rely on apache commons jexl provide expression support in template spreadsheet.
in template, have placeholders such /@v1@/
need replace actual variable value. in either framework, can use ${
, }
signify expression should replaced value. cell value in template spreadsheet.
what ${v1}% of ${v2}?
in java code, create map<string, object>
maps variable names values, e.g.
map<string, object> beans = new hashmap<string, object>(); beans.put("v1", 50); beans.put("v2", 16);
the libraries use map
provide values expressions evaluated.
then, call api entry point create spreadsheet has expressions replaced values. in jett, like:
exceltransformer transformer = new exceltransformer(); transformer.transform(inputtemplatefilename, outputfilename, beans);
in jxls, similar:
xlstransformer transformer = new xlstransformer(); transformer.transformxls(inputtemplatefilename, beans, outputfilename);
the output in either case be, example cell above:
what 50% of 16?
Comments
Post a Comment