使用java读取后,将Excel中的数据存储在列表中

时间:2013-04-09 12:37:18

标签: java arrays apache-poi

我正在使用APACHE POI从excel文件中读取数据。我想将它们存储在列表中(如c中的列表)结果,因为之后我会尝试将它们存储在mysql数据库中,只调用list [0],例如list [1]。我将尝试做的是制作此列表,之后我将使用jdbc驱动程序并给出此列表以在mysql中创建表。 读取excel文件的代码如上:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;

public class readexcel{

@SuppressWarnings({“unchecked”,“unchecked”}) public static void main(String [] args)抛出异常{

//
 // An excel file name. You can create a file name with a full
 // path information.
 //
String filename = "C:\\Users\\xxx\\Documents\\test.xls";

//
// Create an ArrayList to store the data read from excel sheet.
//
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
//
// Create a FileInputStream that will be use to read the
// excel file.
//
fis = new FileInputStream(filename);

 //
 // Create an excel workbook from the file system.
//
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//
// Get the first sheet on the workbook.
//
HSSFSheet sheet = workbook.getSheetAt(0);

 //
  // When we have a sheet object in hand we can iterator on
// each sheet's rows and on each row's cells. We store the
// data read on an ArrayList so that we can printed the
// content of the excel to the console.
 //
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();

List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
 }

sheetData.add(data);
 }
 } catch (IOException e) {
e.printStackTrace();
 } finally { 
 if (fis != null) {
 fis.close();
 }
 }

 showExcelData(sheetData);
  }

 private static void showExcelData(List sheetData) {
  //
    // Iterates the data and print it out to the console.
  //
for (int i = 0; i < sheetData.size(); i++) {
 List list = (List) sheetData.get(i);
for (int j = 0; j < list.size(); j++) {
Cell cell = (Cell) list.get(j);
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
System.out.print(cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
System.out.print(cell.getRichStringCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
}
if (j < list.size() - 1) {
System.out.print(", ");
}
}
System.out.println("");
}
}
}

我必须添加什么来做我解释你的事情?

4 个答案:

答案 0 :(得分:1)

在开始迭代工作表之前初始化数组列表方式, 数组列表必须具有在excel表的行和列迭代中的任何位置保留的范围。

ArrayList myList = new ArrayList()

将这些行放入正在基于行执行的单元迭代循环中

if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) 
{
System.out.print(cell.getNumericCellValue());
myList.add(cell.getNumericCellValue());
} 
else if (cell.getCellType() == Cell.CELL_TYPE_STRING) 
{
System.out.print(cell.getRichStringCellValue());
myList.add(cell.getRichStringCellValue());
} 
else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) 
{
System.out.print(cell.getBooleanCellValue());
myList.add(cell.getBooleanCellValue());
}

现在您处理此列表以将数据插入DataBase

答案 1 :(得分:1)

我发现这个功能可用

public static ArrayList<ArrayList<String>> GetExcelTableInto2DArrayListString(String excelFile, boolean debug){

    ArrayList<ArrayList<String>> OUT = new ArrayList<ArrayList<String>>();  
        File myFile = new File(excelFile); 
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(myFile);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

        // Finds the workbook instance for XLSX file 
        XSSFWorkbook myWorkBook = null;
        try {
            myWorkBook = new XSSFWorkbook (fis);
        } catch (IOException e) {
            e.printStackTrace();
        } 

        // Return first sheet from the XLSX workbook 
        XSSFSheet mySheet = myWorkBook.getSheetAt(0); 

        // Get iterator to all the rows in current sheet 
        Iterator<Row> rowIterator = mySheet.iterator(); 

        // Traversing over each row of XLSX file 
        int count=1;
        while (rowIterator.hasNext()) { 
            Row row = rowIterator.next();
            ArrayList<String> InnerArray = new ArrayList<String>() ;
            if(debug)System.out.print(count + ". \t");
        // 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_STRING: 
                    String c = cell.getStringCellValue();
                    if(debug)System.out.print(c + "\t");
                    InnerArray.add(c);
                    break; 
                case Cell.CELL_TYPE_NUMERIC: 
                    int n = (int) cell.getNumericCellValue();
                    if(debug)System.out.print(n + "\t");
                    InnerArray.add(String.valueOf(n));
                    break; 
                case Cell.CELL_TYPE_BOOLEAN:
                    boolean b = cell.getBooleanCellValue();
                    if(debug)System.out.print(b + "\t");
                    InnerArray.add(String.valueOf(b));
                break; 
                default : 
                    } 
                }
            if(debug)System.out.println("");
            OUT.add(InnerArray);
            count++; 
            }

    return OUT;
}

public static ArrayList<ArrayList<String>> GetExcelTableInto2DArrayListString(String excelFile, boolean debug){ ArrayList<ArrayList<String>> OUT = new ArrayList<ArrayList<String>>(); File myFile = new File(excelFile); FileInputStream fis = null; try { fis = new FileInputStream(myFile); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Finds the workbook instance for XLSX file XSSFWorkbook myWorkBook = null; try { myWorkBook = new XSSFWorkbook (fis); } catch (IOException e) { e.printStackTrace(); } // Return first sheet from the XLSX workbook XSSFSheet mySheet = myWorkBook.getSheetAt(0); // Get iterator to all the rows in current sheet Iterator<Row> rowIterator = mySheet.iterator(); // Traversing over each row of XLSX file int count=1; while (rowIterator.hasNext()) { Row row = rowIterator.next(); ArrayList<String> InnerArray = new ArrayList<String>() ; if(debug)System.out.print(count + ". \t"); // 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_STRING: String c = cell.getStringCellValue(); if(debug)System.out.print(c + "\t"); InnerArray.add(c); break; case Cell.CELL_TYPE_NUMERIC: int n = (int) cell.getNumericCellValue(); if(debug)System.out.print(n + "\t"); InnerArray.add(String.valueOf(n)); break; case Cell.CELL_TYPE_BOOLEAN: boolean b = cell.getBooleanCellValue(); if(debug)System.out.print(b + "\t"); InnerArray.add(String.valueOf(b)); break; default : } } if(debug)System.out.println(""); OUT.add(InnerArray); count++; } return OUT; }

答案 2 :(得分:0)

查看下面的代码

public List<ArrayList<String>> readExcelData2(String excelFile) throws IOException {

    List<ArrayList<String>> depts = new ArrayList<ArrayList<String>>();

    FileInputStream excelFileToRead = new FileInputStream(new File(excelFile));

    XSSFWorkbook wb = new XSSFWorkbook(excelFileToRead);

    XSSFSheet sheet = wb.getSheetAt(0);

    XSSFRow row;
    XSSFCell cell;
    int maxDataCount = 0;

    Iterator<Row> rows = sheet.rowIterator();

    while (rows.hasNext()) {
        row = (XSSFRow) rows.next();
        // skip the first row because it will be header
        if (row.getRowNum() == 0) {
            maxDataCount = row.getLastCellNum();
            continue;
        }

        // if the row is empty stop the loop, do not go further
        if (this.isRowEmpty(row, maxDataCount)) {
            // exit processing
            break;
        }

        // define arraylist object to store list of departments of each row
        ArrayList<String> innerArrayList = new ArrayList<String>();

        for (int cn = 0; cn < maxDataCount; cn++) {
            cell = row.getCell(cn, Row.CREATE_NULL_AS_BLANK);

            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                innerArrayList.add(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_NUMERIC:
                innerArrayList.add(String.valueOf(cell.getNumericCellValue()));
                break;

            default:
                innerArrayList.add(cell.getStringCellValue());
                break;
            }

        }
        depts.add(innerArrayList);

    }
    return depts;
}

public boolean isRowEmpty(Row row, int lastCellNo) {
    for (int c = row.getFirstCellNum(); c < lastCellNo; c++) {
        Cell cell = row.getCell(c, Row.CREATE_NULL_AS_BLANK);
        if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
            return false;
        }
    }
    return true;
}

答案 3 :(得分:0)

将您的条件部分更改为此应该可行:

 if (cell.getCellType() == NUMERIC) {
    System.out.print(cell.getNumericCellValue());
    } else if (cell.getCellType() == STRING) {
    System.out.print(cell.getRichStringCellValue());
    } else if (cell.getCellType() == BOOLEAN) {
    System.out.print(cell.getBooleanCellValue());
    }