我正在学习用java编写excel文件。我已经编写了从excel表创建条形图的代码,我面临着“无法从STRING单元格中获取NUMERIC值”的错误。我不明白如何解决这个问题。是否有人可以帮助我解决问题。
这是代码。
> 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."); } } }
谁能帮助我解决这个问题呢?谢谢你:)
答案 0 :(得分:0)
如果您尝试将字符串保存为Java中的double或integer,它将拒绝此字符串,因为它是强类型语言。您可以改为使用代码行
Integer.parseInt(*desiredVariable*)
或
Double.parseDouble(*desiredVariable*)
将这些字符串更改为正确的数据类型。
答案 1 :(得分:0)
HSSFCell yourCell = sheet.getRow(row).getCell(column);
yourCell.setCellType(Cell.CELL_TYPE_STRING);
String data = yourCell.getStringCellValue();