【问题标题】:Writing HashMap to Excel将 HashMap 写入 Excel
【发布时间】:2015-03-19 05:25:05
【问题描述】:

我的要求是使用 Apache POI 将 HashMap 写入 excel,hashmap 中的键是我的单元格 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。

【问题讨论】:

  • 我想比较两个excel,把区别写在第三张excel表中

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


【解决方案1】:

如果您想比较两个 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;
                }
            }
        }

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-15
      • 1970-01-01
      • 2014-05-21
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      相关资源
      最近更新 更多