📜  使用Apache POI读取和写入数据到excel文件

📅  最后修改于: 2021-10-21 05:21:19             🧑  作者: Mango

在这篇文章的前面,我们介绍了 Apache POI——一种用于与 Microsoft 办公文档交互的Java API。
现在我们将看到如何使用 API 读取和写入 Excel 文件。

写一个excel文件

使用 POI 编写文件非常简单,包括以下步骤:

  1. 创建工作簿
  2. 在工作簿中创建工作表
  3. 在工作表中创建一行
  4. 在工作表中添加单元格
  5. 重复步骤 3 和 4 写入更多数据
// import statements
public class POIforgfgWrite {
public static void main(String[] args)
    {
        // Blank workbook
        XSSFWorkbook workbook = new XSSFWorkbook();
  
        // Create a blank sheet
        XSSFSheet sheet = workbook.createSheet("student Details");
  
        // This data needs to be written (Object[])
        Map data = new TreeMap();
        data.put("1", new Object[]{ "ID", "NAME", "LASTNAME" });
        data.put("2", new Object[]{ 1, "Pankaj", "Kumar" });
        data.put("3", new Object[]{ 2, "Prakashni", "Yadav" });
        data.put("4", new Object[]{ 3, "Ayan", "Mondal" });
        data.put("5", new Object[]{ 4, "Virat", "kohli" });
  
        // Iterate over data and write to sheet
        Set keyset = data.keySet();
        int rownum = 0;
        for (String key : keyset) {
            // this creates a new row in the sheet
            Row row = sheet.createRow(rownum++);
            Object[] objArr = data.get(key);
            int cellnum = 0;
            for (Object obj : objArr) {
                // this line creates a cell in the next column of that row
                Cell cell = row.createCell(cellnum++);
                if (obj instanceof String)
                    cell.setCellValue((String)obj);
                else if (obj instanceof Integer)
                    cell.setCellValue((Integer)obj);
            }
        }
        try {
            // this Writes the workbook gfgcontribute
            FileOutputStream out = new FileOutputStream(new File("gfgcontribute.xlsx"));
            workbook.write(out);
            out.close();
            System.out.println("gfgcontribute.xlsx written successfully on disk.");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

读取excel文件

如果我们将其分步读取,则读取 excel 文件也非常简单。

  1. 从 Excel 工作表创建工作簿实例
  2. 到达所需的工作表
  3. 增加行号
  4. 遍历一行中的所有单元格
  5. 重复步骤 3 和 4,直到读取所有数据
// import statements
public class POIforgfgRead {
public static void main(String[] args)
    {
        try {
            FileInputStream file = new FileInputStream(new File("gfgcontribute.xlsx"));
  
            // Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(file);
  
            // Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);
  
            // Iterate through each rows one by one
            Iterator rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                // For each row, iterate through all the columns
                Iterator cellIterator = row.cellIterator();
  
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    // Check the cell type and format accordingly
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "t");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "t");
                        break;
                    }
                }
                System.out.println("");
            }
            file.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出:
输出

有时您需要读取不同位置的文件:您可以这样做:

private static final String FILE_NAME
    = "C:\\Users\\pankaj\\Desktop\\projectOutput\\mobilitymodel.xlsx";
public static void write() throws IOException, InvalidFormatException
{
    InputStream inp = new FileInputStream(FILE_NAME);
    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(0);
    ........
}

您可以使用以下代码附加到现有文件:

private static final String FILE_NAME
    = "C:\\Users\\pankaj\\Desktop\\projectOutput\\blo.xlsx";
public static void write() throws IOException, InvalidFormatException
{
    InputStream inp = new FileInputStream(FILE_NAME);
    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(0);
    int num = sheet.getLastRowNum();
    Row row = sheet.createRow(++num);
    row.createCell(0).setCellValue("xyz");
    .....
        ..
        // Now this Write the output to a file
        FileOutputStream fileOut = new FileOutputStream(FILE_NAME);
    wb.write(fileOut);
    fileOut.close();
}

参考 :
https://poi.apache.org/
https://poi.apache.org/spreadsheet/examples.html
https://poi.apache.org/apidocs/