2017-06-15 66 views
0

我正在学习使用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 :)

+1

重新格式化您的代码,使其首先可读;) – HieuHT

回答

0

如果您尝试将字符串保存为Java中的double或integer,则它会拒绝此操作,因为它是强类型语言。您可以改为使用的代码行

Integer.parseInt(*desiredVariable*) 

Double.parseDouble(*desiredVariable*) 

改变这些字符串放到正确的数据类型。

+0

它不工作,因为方法解析不适用于ArrayList ..任何其他建议? –

+0

你能指出导致错误的问题中的具体行吗?它应该在你的控制台中告诉你。 – JoshKopen

+0

当我使用解析方法时,它显示一个错误,解析不适用于字符串数组列表,如用于在程序开始时将列表1声明为数组列表。当我将数组列表字符串的声明更改为简单数组时,它显示错误行46,47和48中,添加方法不适用于简单字符串..不能帮助此.. –

0
HSSFCell yourCell = sheet.getRow(row).getCell(column); 
    yourCell.setCellType(Cell.CELL_TYPE_STRING); 
    String data = yourCell.getStringCellValue(); 
+0

如何在我的代码中使用它?因为米没有得到它。如果你很好地编辑代码?谢谢 –

相关问题