2016-01-19 66 views
0

我有一个看起来像这样的excel文件。寻找将col1细胞分成单独部分(物品中的物品)的方法。在Excel中将单元拆分为字符串 - Apache POI JAVA

 col1  col2 col3 col4 
     ----------------------------- 
row1 | 2,3,1 _  1  w 
row2 | 3,2,7 _  2  x 
row3 | _  _  3  y 
row4 | 4,9  _  4  z 

CODE:

import org.apache.poi.ss.usermodel.*; 
import org.apache.poi.xssf.usermodel.*; 

public class Expy { 
    public static void main(String[] args) { 
     try { 
     FileInputStream file = new FileInputStream(new File("C:\\Users\\...\\Bioactives25s.xlsx")); 
     XSSFWorkbook workbook = new XSSFWorkbook(file); 
     XSSFSheet worksheet = workbook.getSheetAt(0); 
     for (int rowIndex = 0; rowIndex<50000; rowIndex++){ 
      for (int columnIndex = 0; columnIndex<30; columnIndex++){ 
      XSSFCell cell = worksheet.getRow(rowIndex).getCell(0); 
      XSSFCell COL1 = worksheet.getRow(rowIndex).getCell(2); 
      XSSFCell COL2 = worksheet.getRow(rowIndex).getCell(3); 

      //important region 
      String data = ??? ; 
      String[] items = cell.split(","); 
      //for (String item : items) 

      if(cell != null){ 
      continue;} 
      if(cell == COL1){ 
       System.out.print("it worked!!!"); 
      } 
      if(cell == null){ 
       continue; 
      } 

我不知道放什么的问号区域。我尝试了放入“文件”,我试过“工作表”,不知道我应该写什么来使excel第1列读作字符串,所以我可以迭代它。对Java很新颖。

相关:http://kodejava.org/how-do-i-split-a-string/

回答

2

使用XSSFCell.getStringCellValue()

XSSFCell cell = worksheet.getRow(rowIndex).getCell(0); 
String contents = cell.getStringCellValue(); 

String[] items = contents.split(","); 

for (String item : items) { 
    System.out.println("Found csv item: " + item); 
} 

阅读Apache POI documentation以获取更多信息。

+1

非常感谢! – Patel

+0

高兴地帮助你:-) –