将HashMap编写到Excel

时间:2015-03-19 05:25:05

标签: java hashmap apache-poi export-to-excel

我的要求是使用Apache POI将HashMap写入excel,hashmap中的键是我的cell-id,hashmap中的值是要设置到该单元格中的值。 以下是我的代码:

public static final String[] ExcelColumns = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
    "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", 
    "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", 
    "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS",
    "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM",
    "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG",
    "DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ"};

public static int row(Map.Entry pair) {
        //System.out.println("The row is:"+k);
        return new Integer(pair.getKey().toString().substring(1));
              }
public static int column(Map.Entry pair) {
        String indexVal = pair.getKey().toString().substring(0, 1);
        String[] ExcelColumns = CompareExcelDAO.ExcelColumns;
        int index = 0;
        for (int i = 0; i < ExcelColumns.length; ++i) {
              if (indexVal.equals(ExcelColumns[i])) {
                    index = i;
              }
        }
        return index+1;
  }
public void CopyContentsOfExcel(HSSFWorkbook workbook, HSSFSheet sheet,
              String ExcelPath_1, int i, HashMap getMismatchMap)
              throws IOException {          
        int rownum = sheet.getLastRowNum()+2; // to check last used row in Excel            
        //CompareExcelDAO mapDao = new CompareExcelDAO();
              Iterator it1 = getMismatchMap.entrySet().iterator();
              while (it1.hasNext()) {
                    Map.Entry pair = (Map.Entry) it1.next();
                    int r = row(pair) + rownum;
                    int c= column(pair);
                    System.out.println("c = "+c+"     r = "+r);
                    System.out.println("Key: "+pair.getKey()+" "+"Value: "+pair.getValue());
                    sheet.createRow(r).createCell(c).setCellValue(pair.getValue().toString());

              }}

问题是它只将一对键/值打印到两个固定单元格中,在调试模式下,所有行/列值都按预期显示,但是当我打开工作表时,只打印一个值。 http://www.tagwith.com/question_1103031_printing-a-hashmap-to-excel-using-jxl-api,此站点提供了一种使用jxl将Hashmap写入Excel的方法,但我的所有项目都使用Apache POI。

2 个答案:

答案 0 :(得分:0)

我不确定如何为多行提供散列映射。我有类似的问题,如下所示。我将创建一个类似于ColumnNameColumnValue的地图,我会将其添加到多个列的地图中。然后将类似的多个行的地图映射到List,并且我将它写为excel文件。你可以试试这个。

public static void main(String[] p) throws Exception{
    List<Map<String, String>> collection = new ArrayList<>();
    Map<String, String> row1 = new LinkedHashMap<>();
    row1.put("ID","1");
    row1.put("Name","pop");
    collection.add(row1);
    Map<String, String> row2 = new LinkedHashMap<>();
    row2.put("ID","2");
    row2.put("Name","lop");
    collection.add(row2);
    writeCollection(new File("excel1.xlsx"),"sheet1",collection);
}

private static void writeCollection(File file, String sheetName, List<Map<String, String>> collection) throws Exception {
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = workBook.getSheet(sheetName);
        int rows = sheet.getLastRowNum();
        fileInputStream.close();
        rows = rows + 1;

        for (int index = 0; index < collection.size(); index++) {
            XSSFRow row = sheet.createRow(rows++);
            Map<String, String> rowObject = collection.get(index);
            for (String columnName : rowObject.keySet()) {
                int cellIndex = getColumnIndex(sheet, columnName);
                if (cellIndex != -1) {
                    XSSFCell cell = row.createCell(cellIndex);
                    cell.setCellValue(rowObject.get(columnName));
                }
            }
        }
        FileOutputStream out = new FileOutputStream(file);
        workBook.write(out);
        out.close();

    } catch (Exception e) {
        throw e;
    }
}

public static int getColumnIndex(XSSFSheet sheet, String columnName) {
    int columnIndex = -1;
    try {
        int colNum = sheet.getRow(0).getLastCellNum();
        XSSFRow firstRow = sheet.getRow(0);
        for (int colIndex = 0; colIndex < colNum; colIndex++) {
            XSSFCell cell = firstRow.getCell(colIndex);
            if (cell.toString().equals(columnName)) {
                columnIndex = colIndex;
            }
        }
    } catch (Exception e) {
        throw e;
    }
    return columnIndex;
}

答案 1 :(得分:0)

如果你想比较两个excel并在第三个中写出差异, 创建一个新的工作簿和工作表,并将其传递给一个方法,您可以打开两个Excel,并比较下面的内容:

while (file1cellIterator.hasNext()&& file2cellIterator.hasNext()) {
                Cell file1cell = (Cell) file1cellIterator.next();
                Cell file2cell = (Cell) file2cellIterator.next();

                org.apache.poi.ss.usermodel.Cell cell = row.createCell(cellnum++);

                switch (file1cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    if ((file1cell.getBooleanCellValue())==(file2cell.getBooleanCellValue())){
                        ((org.apache.poi.ss.usermodel.Cell) cell).setCellValue(file1cell.getBooleanCellValue());
                            }
                    else if((file1cell.getBooleanCellValue())!=(file2cell.getBooleanCellValue())){
                        ((org.apache.poi.ss.usermodel.Cell) cell).setCellValue(file1cell.getBooleanCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if ((file1cell.getNumericCellValue())==(file2cell.getNumericCellValue())){
                        ((org.apache.poi.ss.usermodel.Cell) cell).setCellValue(file1cell.getNumericCellValue());
                                                        }
                    else if((file1cell.getNumericCellValue())!=(file2cell.getNumericCellValue())){
                        ((org.apache.poi.ss.usermodel.Cell) cell).setCellValue((file1cell.getNumericCellValue())-(file2cell.getNumericCellValue()));
                                                }
                    break;
                case Cell.CELL_TYPE_STRING:
                    if ((file1cell.getStringCellValue())==(file2cell.getStringCellValue())){
                        ((org.apache.poi.ss.usermodel.Cell) cell).setCellValue(file1cell.getStringCellValue());
                            }
                    else if((file1cell.getStringCellValue())!=(file2cell.getStringCellValue())){
                        ((org.apache.poi.ss.usermodel.Cell) cell).setCellValue((file1cell.getStringCellValue())+(file2cell.getStringCellValue()));
                    }
                    break;
                default:
                    ((org.apache.poi.ss.usermodel.Cell) cell)
                            .setCellValue(file1cell.getStringCellValue());
                    break;
                }
            }
        }