我正在学习使用java读取和写入excel文件。我已经编写了用于从Excel工作表创建条形图的代码,并且我正面临着“无法从STRING单元格获取NUMERIC值”的错误。我不知道如何解决这个问题..有没有人可以帮助我解决问题。从java中的字符串单元格获取数值
这里是代码。
> 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."); } } }
谁能帮我解决这个问题? Thankyou :)
重新格式化您的代码,使其首先可读;) – HieuHT