简体   繁体   中英

What should I import to be able to use the following code correctly?

Hi Im trying to read an Excel file into my android application. I tried using this code:

try {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row;
    HSSFCell cell;

    int rows; // No of rows
    rows = sheet.getPhysicalNumberOfRows();

    int cols = 0; // No of columns
    int tmp = 0;

    // This trick ensures that we get the data properly even if it doesn't start from first few rows
    for(int i = 0; i < 10 || i < rows; i++) {
        row = sheet.getRow(i);
        if(row != null) {
            tmp = sheet.getRow(i).getPhysicalNumberOfCells();
            if(tmp > cols) cols = tmp;
        }
    }

    for(int r = 0; r < rows; r++) {
        row = sheet.getRow(r);
        if(row != null) {
            for(int c = 0; c < cols; c++) {
                cell = row.getCell((short)c);
                if(cell != null) {
                    // Your code here
                }
            }
        }
    }
} catch(Exception ioe) {
    ioe.printStackTrace();
}

I was wondering if I should import anything or any library?

If you are using Eclipse as your IDE (I assume you are since this is Android related) you can press ctrl + shift + O and it will automatically import anything you need, assuming you have the libraries included in your build path. However, it sounds like you don't have the Apache POI libraries. First you need to download the libraries. After they are downloaded you need to add them to your build path using the following method: (Again assuming that you are using Eclipse as your IDE)

  1. Right click your project in the project explorer.
  2. Choose Build Path -> Configure Build Path
  3. Choose the library tab.
  4. Click "Add JARs..."
  5. Find and select the JAR file that you just downloaded. (You might need to copy the JAR into your project so that you are able to select it)

Alternatively, you can add the library to one of your project folders (typically a "lib" folder), right click it in Eclipse and select "Add to Build Path".

It should now be added to your build path. Again try hitting ctrl + shift + O and the necessary imports will be made for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM