HashMap是一个包含ArrayList的函数

时间:2013-04-11 12:18:26

标签: java hashmap

如何将我的函数中的sheetData放入Hashmap?

private static void showExcelData(List sheetData){

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("");
}

}

程序正在读取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) throws Exception {

String filename = "C:\\Users\\xxxx\\Documents\\test5.xls";


List sheetData = new ArrayList();
FileInputStream fis = null;
try {

fis = new FileInputStream(filename);


HSSFWorkbook workbook = new HSSFWorkbook(fis);

HSSFSheet sheet = workbook.getSheetAt(0);

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) {

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("");
 }
 }
 }

1 个答案:

答案 0 :(得分:0)

目前尚不清楚,但我认为您在询问如何使用策略设计模式,因此您使用Map而不是if .. else if

所以你需要

  1. 编写一个表示抽象操作的接口或抽象基类。
  2. 编写类型到操作的映射(从单元格类型到操作的Map
  3. 更改您的showExcelData方法以使用该映射来查找要使用的操作,然后委派给该操作。
  4. 但我不会为你编写代码,因为这不是代码编写服务。