I'm new to Java and Apache POI, but I got this task where I have to read from the command line the name of the Excel file and the name and values of the columns that needs to be modified.
So in the end the application will run like this: java test -f test.xls -i B2=10;B3=20;B4=30
I have created a map that holds the cell name and their values, but I don't know how to use this map in order to access cells by their name (eg.: B2) and set the new value (eg.: 10).
My code so far is bellow:
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.*;
public class ReadExcel {
public static void main(String[] args) throws FileNotFoundException, IOException {
// Will contain cell name / value pair for input cells and output cells
Map<String, String> inputCellsMap = new HashMap<String, String>();
Map<String, String> outputCellsMap = new HashMap<String, String>();
// Open the Excel file
FileInputStream file = new FileInputStream(new File(args[1]));
// Get the current workbook
HSSFWorkbook workbook = new HSSFWorkbook(file);
// Get the first sheet of the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
// Get the input cells that need to be modified and
// store their name and value in the inputCellsMap
for (String element : args[3].split(";")) {
inputCellsMap.put(element.split("=")[0], element.split("=")[1]);
}
// Loop through the cells that need to be modified and
// set the new value in the Excel document
Iterator<Entry<String,String>> iterator = inputCellsMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String,String> entry = (Map.Entry<String,String>) iterator.next();
// TODO
// Get cells by name and set their new value
//System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());
}
workbook.close();
}
}