2017-06-15 71 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

如何在我的代碼中使用它?因爲米沒有得到它。如果你很好地編輯代碼?謝謝 –

相關問題