2016-03-03 2 views
0

Я хочу прочитать файл xls с помощью JXl, где имя файла xls всегда меняется, как читать, пожалуйста, помогите. я попытался ниже кодКак справиться с изменением имен файлов. Использование jxl?

FileInputStream filepath = new FileInputStream("C:\\Users\\sameer.joshi\\Downloads\\*.xls"); 

FileInputStream filepath = new FileInputStream("C:\\Users\\sameer.joshi\\Downloads\\"); 
+0

Следовать [http://stackoverflow.com/questions/14980717/what-is-the-better-api-to-reading-excel-sheets-in- java-jxl-or-apache-poi] –

+0

@manikant gautam Я прошел через эту ссылку, я не понял, что вы пытаетесь сказать –

+0

Добавьте все .xls имя_файла внутри списка и следуйте методу обработки файла .xls. –

ответ

1
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.Iterator; 
import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.Row; 

public class Test {  
public static void main(String[] args) throws FileNotFoundException, IOException { 

    File directory = new File("C:\\Users\\sameer.joshi\\Downloads\\"); 
    File[] all_XLS_Files = directory.listFiles(); //all files in that directory 

    for (File file : all_XLS_Files) { // iterate through all files in that directory 
     if(file.getName().endsWith(".xls")){ // select only xls files 
     //do something with your xls files here 
     //for example print out the file name 
     System.out.println(file.getName()); 
     //or read one or all of them 
     FileInputStream fileInputStream = new FileInputStream(new File(file.getPath())); 

     //Get the workbook instance for XLS file 
     HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); 

     //Get first sheet from the workbook 
     HSSFSheet sheet = workbook.getSheetAt(0); 

     //Iterate through each rows from first sheet 
     Iterator<Row> rowIterator = sheet.iterator(); 
     while(rowIterator.hasNext()) { 
      Row row = rowIterator.next(); 

      //For each row, iterate through each columns 
      Iterator<Cell> cellIterator = row.cellIterator(); 
      while(cellIterator.hasNext()) { 

       Cell cell = cellIterator.next(); 

       switch(cell.getCellType()) { 
        case Cell.CELL_TYPE_BOOLEAN: 
         System.out.print(cell.getBooleanCellValue() + "\t\t"); 
         break; 
        case Cell.CELL_TYPE_NUMERIC: 
         System.out.print(cell.getNumericCellValue() + "\t\t"); 
         break; 
        case Cell.CELL_TYPE_STRING: 
         System.out.print(cell.getStringCellValue() + "\t\t"); 
         break; 
       } 
      } 
      System.out.println(""); 
     } 
     fileInputStream.close(); 
     FileOutputStream out = 
      new FileOutputStream(new File(file.getPath())); 
     workbook.write(out); 
     out.close(); 
     } 
    } 
} 

} 
+0

вы также можете прочитать этот учебник: [Чтение/запись файла Excel в Java с использованием Apache POI] (http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/) – Eritrean

1

Try, чтобы добавить все имена файлов в списке и прочитать все данные файла Excel.

List<String>ArrayList xlsFiles=new ArrayList<String>(); 
xlsFiles.add("your all files Names"); 
for (String str:xlsFiles) { 
    readExcellData(str); 
} 

public List<String> readExcellData(String fileNameToProcess) throws IOException { 
    List<String> dataList = new ArrayList<String>(); 
    List<Integer> rowNo=new ArrayList<Integer>(); 
    List<Integer> colNo=new ArrayList<Integer>(); 
    int countRow=1; 
    int countCol=1; 
    try { 

     FileInputStream fis = new FileInputStream(file); 
     HSSFWorkbook wb = new HSSFWorkbook(fis); 
     HSSFSheet sheet = wb.getSheetAt(0); 
     Iterator<Row> rowIterator = sheet.iterator(); 

     while (rowIterator.hasNext()) { 
      rowNo.add(countRow); 
      Row row = rowIterator.next(); 
      Iterator<Cell> cellIterator = row.cellIterator(); 
      while (cellIterator.hasNext()) { 
       cell = cellIterator.next(); 
       switch (cell.getCellType()) { 
       case Cell.CELL_TYPE_STRING: { 
        dataList.add(cell.getStringCellValue()); 
        System.out.println(cell.getStringCellValue()); 
       } 
        break; 
       } 
      } 
     } 
     return dataList; 
    } catch (FileNotFoundException ee) { 
     ee.printStackTrace(); 
    } catch (IOException ee) { 
     ee.printStackTrace(); 
    } 

    return dataList; 
} 
0

Я думаю, что проблема заключается не в том, как читать файл xls, а в том, как иметь дело с изменяющимися именами файлов. если это так, попробуйте использовать FilenameFilter, чтобы получить ваши .xls-файлы. Пример:

public class Test { 

public static void main(String[] args) throws FileNotFoundException, IOException { 

    File directory = new File("C:\\Users\\sameer.joshi\\Downloads\\"); 

    //get all files which ends with ".xls" 
    FilenameFilter textFilter = new FilenameFilter() { 
     public boolean accept(File dir, String name) { 
      return name.endsWith(".xls"); 
     } 
    }; 

    // all xls files are listed in this File[] array 
    File[] files = directory.listFiles(textFilter); 
    // iterate through your array and do something 

    for (File file : files) { 
     //read your .xls files here 
     System.out.println(file.getCanonicalPath()); 
    } 
} 

}

+0

если у меня есть более одного файла xls в этой dierectory, что он делает? –

Смежные вопросы