Apache poi + Java:写入工作表而不删除现有数据

时间:2018-03-21 01:05:44

标签: java excel apache-poi

我需要检查工作表是否存在。 如果存在,则必须键入下一个现有行,不要创建新工作表。

您目前正在删除当前的电子表格,我在电子表格中只写了一行。

我该如何解决?

public class ApachePOIExcelWrite {
    private static final String FILE_NAME = "c:/viagem.xlsx";

    XSSFWorkbook workbook = new XSSFWorkbook();

    //name Sheet
    XSSFSheet sheet = workbook.createSheet("Viagem");

    Object[][] datatypes = {

        //head colums
        {
            "Destino",
            "Valor por pessoa",
            "Aeroporto",
            "Hotel",
            "data Pesquisa",
            "Hora Pesquisa"
        },


        {
            destino,
            pega_valor,
            aeroporto.replace("GRU", "Guarulhos").replace("CGH", "Congonhas"),
            hotel.replaceAll("Pontos", "Estrelas"),
            data_da_pesquisa.format(d),
            hora_da_pesquisa.format(d)

        }
    };

    int rowNum = 0;

    System.out.println("Creating excel");

    for (Object[] datatype: datatypes) {
        Row row = sheet.createRow(rowNum++);
        int colNum = 0;
        for (Object field: datatype) {
            Cell cell = row.createCell(colNum++);
            if (field instanceof String) {
                cell.setCellValue((String) field);
            } else if (field instanceof Integer) {
                cell.setCellValue((Integer) field);
            }
        }
    }

    try {
        FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
        workbook.write(outputStream);
        workbook.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

2 个答案:

答案 0 :(得分:1)

/**
 * Opens an existing sheet or creates a new one if the given sheet name doesn't exist. 
 * Appends values after the last existing row.
 */
public static void main(String[] args) throws IOException {
    XSSFWorkbook workbook = new XSSFWorkbook("C:\\Users\\Administrator\\Desktop\\test.xlsx");
    Sheet sheet = workbook.getSheet("Sheet1");
    if (sheet == null)
        sheet = workbook.createSheet("Sheet1");

    Object[][] values = {{"A2", "B2", "C2"}, {"A3","B3","C3","D3"}};
    int initRow = sheet.getLastRowNum() + 1;
    int initCol = 0;
    for (int i = 0; i < values.length; i++) {
        Object[] rowValues = values[i];
        for (int j = 0; j < rowValues.length; j++) {
            Object value = rowValues[j];
            writeValueToCell(value, initRow + i, initCol + j, sheet);
        }
    }

    try {
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\output.xlsx");
        workbook.write(fos);
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void writeValueToCell(Object value, int rowIdx, int colIdx, Sheet sheet) {
    Row row = sheet.getRow(rowIdx);
    Cell cell;
    if (row == null) {
        cell = sheet.createRow(rowIdx).createCell(colIdx);
    } else {
        cell = row.getCell(colIdx);
        if (cell == null)
            cell = row.createCell(colIdx);
    }

    if (value == null)
        cell.setCellType(Cell.CELL_TYPE_BLANK);
    else if (value instanceof String)
        cell.setCellValue(value.toString());
    else if (value instanceof Integer)
        cell.setCellValue((Integer) value);
    else if (value instanceof Double)
        cell.setCellValue((Double) value);
    else if (value instanceof Date) {
        cell.setCellValue((Date) value);
        CellStyle style = sheet.getWorkbook().createCellStyle();
        style.setDataFormat(sheet.getWorkbook().getCreationHelper().createDataFormat().getFormat(("yyyy/m/d")));
        cell.setCellStyle(style);
    } else {
        cell.setCellValue("Unknown type");
    }
}

答案 1 :(得分:0)

要检查工作表是否已存在,您可以使用workbook.getSheet("name")。稍后,您可以根据需要创建新工作表。