将 HashMap 写入 Excel

Writing HashMap to Excel

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

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

              }}

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

我不确定您如何拥有多行的散列图。我遇到了类似的问题,如下所示。我将创建一个具有 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;
}

如果你想比较两个 excel 并在第三个中写差异, 创建一个新工作簿和 sheet 并将其传递给一个方法,您可以在其中打开两个 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;
                }
            }
        }