0

如何将sheetData下面的函数放入 Hashmap?

私人静态无效showExcelData(列表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("");
 }
 }
 }
4

1 回答 1

0

目前尚不清楚,但我认为您在问如何使用 Strategy 设计模式,所以您使用 aMap而不是if.. else if

所以你需要

  1. 编写表示抽象操作的接口或抽象基类。
  2. 编写类型到操作的映射(Map从单元类型到操作。
  3. 更改您的showExcelData方法以使用该映射来查找要使用的操作,然后委托给该操作。

但我不会为你编写代码,因为这不是代码编写服务。

于 2013-04-11T12:29:44.883 回答