Reputation: 13
I am learning reading and writing excel files with java. i have written code for creating the bar chart from the excel sheet and i m facing the error that " Cannot get a NUMERIC value from a STRING cell". i am not understanding how to resolve the issue .. Is anyone could help me getting resolve the issue .
here is code .
> import java.io.*; import java.util.*;
>
> import org.jfree.data.*; import org.jfree.chart.JFreeChart; import
> org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities;
> import org.jfree.chart.plot.PlotOrientation; import
> org.apache.poi.hssf.usermodel.HSSFRow; import
> org.apache.poi.hssf.usermodel.HSSFCell; import
> org.apache.poi.hssf.usermodel.HSSFSheet; import
> org.apache.poi.hssf.usermodel.HSSFWorkbook; import
> org.jfree.data.category.DefaultCategoryDataset; import
> org.apache.poi.ss.usermodel.Cell;
>
>
> public class BARCHART{ public static void main(String[]args){ short
> a=0; short b=1; int i=0; ArrayList<String> list1=new
> ArrayList<String>(); ArrayList<Integer> list2=new
> ArrayList<Integer>();
>
> String x; int y=0; String filename ="Student Grading Report.xls";
>
>
> if(filename != null && !filename.equals("")){ try{ FileInputStream fs
> =new FileInputStream(filename); HSSFWorkbook wb = new HSSFWorkbook(fs); for(int k = 0; k < wb.getNumberOfSheets(); k++){
> int j=i+1; HSSFSheet sheet = wb.getSheetAt(k); int rows =
> sheet.getPhysicalNumberOfRows(); for(int r = 1; r < rows; r++){
> HSSFRow row = sheet.getRow(r); int cells =
> row.getPhysicalNumberOfCells(); HSSFCell cell1 = row.getCell(a);
>
> x =(String) cell1.getStringCellValue(); HSSFCell cell2 =
> row.getCell(b); y =(int) cell2.getNumericCellValue();
>
> list1.add(new String(x)); list2.add(new Integer(y)); } i++; }
> }catch(Exception e){ System.out.println(e);
>
> }
>
> } DefaultCategoryDataset dataset = new DefaultCategoryDataset();
> for(int j=0;j<list2.size();j++){
> dataset.setValue((double)list2.get(j), "Marks",
> list1.get(j).toString()); } JFreeChart chart =
> ChartFactory.createBarChart("BarChart","Marks", "St_Id", dataset,
> PlotOrientation.VERTICAL, false,true, false); try {
> ChartUtilities.saveChartAsJPEG(new File("chart.jpg"), chart,400, 300);
> } catch (IOException e) { System.out.println("Problem in creating
> chart."); } } }
anyone one who can help me in resolving such issue? Thankyou :)
Upvotes: 1
Views: 911
Reputation: 593
HSSFCell yourCell = sheet.getRow(row).getCell(column);
yourCell.setCellType(Cell.CELL_TYPE_STRING);
String data = yourCell.getStringCellValue();
Upvotes: 0
Reputation: 960
If you try to save a string into a double or integer in Java, it will reject this as it is a strongly typed language. You can instead use the lines of code
Integer.parseInt(*desiredVariable*)
or
Double.parseDouble(*desiredVariable*)
to change these strings into the right data type.
Upvotes: 1