Java 使用ApachePOI读取复杂的xlsx

Java 使用ApachePOI读取复杂的xlsx,java,apache-poi,Java,Apache Poi,嗨,我想使用ApachePOI读取下面复杂的xlsx文件 InputStream inputStream = content.getInputStream(); XSSFWorkbook wb = new XSSFWorkbook(inputStream); XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row; XSSFCell cell; Iterator rows =

嗨,我想使用ApachePOI读取下面复杂的xlsx文件

InputStream inputStream = content.getInputStream();
        XSSFWorkbook wb = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = wb.getSheetAt(0);
        XSSFRow row;
        XSSFCell cell;

        Iterator rows = sheet.rowIterator();

        while (rows.hasNext())
        {
            row=(XSSFRow) rows.next();
            Iterator cells = row.cellIterator();
            while (cells.hasNext())
            {
                cell=(XSSFCell) cells.next();
                if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
                {
                    System.out.print(cell.getStringCellValue()+" ");
                }
                else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
                {
                    System.out.print(cell.getNumericCellValue()+" ");
                }
            }
        }
以上代码用于读取文件

如何读取xlsx文件并准备对象

Guest Name = abc
Email = abc@mail.com

要遵循的步骤:
1.导入所有Apache POI和相关库
2.使用下面提到的代码,下面的类名是ReadFile.java

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadFile {
    public static void main(String[] args) {
        File content = new File("/home/mohit/file.xlsx");
        try {
            FileInputStream stream = new FileInputStream(content);
            XSSFWorkbook wb = new XSSFWorkbook(stream);
            XSSFSheet sheet = wb.getSheetAt(0);
            XSSFRow row;
            XSSFCell cell;
            Iterator rows = sheet.rowIterator();
            int totalIteration = 0;
            String total = "";
            int currentIterationNumber= 0;

            Guest guest = new Guest();
            List<Guest> guestList = new ArrayList<>();
            List<Room> roomList = new ArrayList<>();

            while (rows.hasNext()) {
                totalIteration++;
                currentIterationNumber++;
                int cellIndicator= 0;
                row = (XSSFRow) rows.next();
                Iterator cells = row.cellIterator();
                Room room = new Room();

                // Each cell
                while (cells.hasNext()) {
                    cellIndicator++;
//                    System.out.print("\nCurrent CellNo :"+cellIndicator+"    ");
                    cell = (XSSFCell) cells.next();

                    // Get Name and Invoice Number
                    if (currentIterationNumber==1){
                        if (cellIndicator==2){
                            guest.setGuestName(cell.getStringCellValue());
                        }
                        if (cellIndicator == 4){
                            guest.setInvoiceNumber((int) cell.getNumericCellValue());
                        }
                    }
                    // Get ConfirmationNumber and EmailAddress
                    if (currentIterationNumber==2){
                        if (cellIndicator==2){
                            guest.setGuestEmail(cell.getStringCellValue());
                        }
                        if (cellIndicator == 4){
                            guest.setConfirmationNumber((int) cell.getNumericCellValue());
                        }
                    }
                    // Get Address and Arrival Dates
                    if (currentIterationNumber==3){
                        if (cellIndicator==2){
                            guest.setGuestAddress(cell.getStringCellValue());
                        }
                        if (cellIndicator == 4){
                            cell.setCellType(CellType.STRING);
                            guest.setArrivalDate(cell.getStringCellValue());
                        }
                    }
                    // Get and Append Address & Departure date
                    if (currentIterationNumber==4){
                        if (cellIndicator==2){
                            guest.setGuestAddress(guest.getGuestAddress()+", "+cell.getStringCellValue());
                        }
                        if (cellIndicator == 4){
                            cell.setCellType(CellType.STRING);
                            guest.setDepartureDate(cell.getStringCellValue());
                        }
                    }
                    // Get and Append Address & RoomType
                    if (currentIterationNumber==5){
                        if (cellIndicator==2){
                            cell.setCellType(CellType.STRING);
                            guest.setGuestAddress(guest.getGuestAddress()+", "+cell.getStringCellValue());
                        }
                        if (cellIndicator == 4){
                            cell.setCellType(CellType.STRING);
                            guest.setRoomType(cell.getStringCellValue());
                        }
                    }

                    // Get and Append Address & Reference
                    if (currentIterationNumber==6){
                        if (cellIndicator==2){
                            guest.setGuestAddress(guest.getGuestAddress()+", "+cell.getStringCellValue());
                        }
                        if (cellIndicator == 4){
                            cell.setCellType(CellType.STRING);
                            guest.setReference(cell.getStringCellValue());
                        }
                    }

                    // Get Stays Data and map to Room Class
                    if (currentIterationNumber>7) {
//                        System.out.print("Starting Stay..."+cellIndicator);
                        if (cellIndicator == 1) {
                            cell.setCellType(CellType.STRING);
//                            System.out.print("Stay Date:"+cell.getStringCellValue());
                            room.setStayDate(cell.getStringCellValue());
                        }

                        if (cellIndicator == 2) {
//                            System.out.print("   Item:"+cell.getStringCellValue());
                            room.setItem(cell.getStringCellValue());
                        }
                        if (cellIndicator == 3) {
//                            System.out.print("   Quantity:"+cell.getNumericCellValue());
                            room.setQuantity((int) cell.getNumericCellValue());
                        }
                        if (cellIndicator == 4) {
                            if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING) {
//                                System.out.print("   Rate:"+cell.getNumericCellValue());
                                room.setRate((int) cell.getNumericCellValue());
                            }
                        }
                        if (cellIndicator == 5) {
//                            System.out.print("   Amount:"+cell.getNumericCellValue());
                            room.setAmount((int) cell.getNumericCellValue());
//                        System.out.print("\nStayDate: "+room.getStayDate()+"   Item: "+room.getItem()+"    Quantity:  "+room.getQuantity()
//                        +"  Rate: "+room.getRate()+"    Amount:"+room.getAmount()+" \n");
//
                            System.out.print("\nAdding Room to the list");
                            roomList.add(room);
                        }

                    }

                    // Check if Current Row is total row
                    if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                        total = cell.getStringCellValue();
                    }

                    // End Collecting for Guest here when you see "Total"
                    if (cellIndicator == 4 && total.equals("Total")){
                        guest.setRoomList(roomList);
                        guestList.add(guest);
                        System.out.print("\nSaving "+guest.getGuestName()+" details with count "+roomList.size());


                        // Perform you DB Operation here

                        // Reset Counter and RoomList
                        guest = new Guest();
                        currentIterationNumber=0;
                        roomList.clear();
                    }
                }

            }

            for (Guest guest1:guestList) {
                System.out.print("\n---- Collected Data: \n Name:"+guest1.getGuestName()+"   InvoiceNo: "+guest1.getInvoiceNumber()
                        +"  Email: "+guest1.getGuestEmail()+"    Confirmation No: "+guest1.getConfirmationNumber()+ "     Address: "+guest1.getGuestAddress()
                        +"   Arrival: "+guest1.getArrivalDate()+"    Dep:"+guest1.getDepartureDate()+"    RoomType: "+guest1.getRoomType()
                        +"      Ref:"+guest1.getReference()+"   Room Count: "+guest1.getRoomList().size());
            }




        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

我还可以分享一个示例项目。如果anwser有效,请接受它。
我已经在这里测试过了。

我的控制台输出:

----收集的数据:
姓名:abc发票编号:0电子邮件:abc@mail.com确认号:123
地址:xxxx,xxxx,119062,印度到达:42911部门:42916
房间类型:一床房城市视图参考:管理
----收集的数据:
名称:xtf发票编号:0电子邮件:xtf@mail.com确认号:456
地址:xxxx,xxxx,119062,印度到达:42911部门:42916
房间类型:单床房间城市视图参考:管理



您仍然需要注意日期的转换,您可以根据修改代码。

Do停留日期将始终为6天??不,它将是可变的。您能否以excel格式共享上述数据并共享可下载的链接,以便我可以提供您可以直接访问的代码use@mohitsharma链接已添加。thanx更新代码为soonThanks bro。为什么房间没有多个房间list@boycod3您可以更改它,我这样做只是为了工作,所以我想创建这样的关系,这里的主要内容是:currentIterationNumber和cellIndicator@boycod3在我提到的评论中”//Perform You DB Operation here“在这里您可以添加DB呼叫。房间列表对于每个客人来说都很常见,甚至他们也不一样。
public class Guest {
    private String guestName;
    private String guestEmail;
    private String guestAddress;
    private int invoiceNumber;
    private int confirmationNumber;
    private String arrivalDate;
    private String departureDate;
    private String roomType;
    private String reference;
    private int totalCharge;
    private List<Room> roomList;

    public List<Room> getRoomList() {
        return roomList;
    }

    public void setRoomList(List<Room> roomList) {
        this.roomList = roomList;
    }

    public String getGuestName() {
        return guestName;
    }

    public void setGuestName(String guestName) {
        this.guestName = guestName;
    }

    public String getGuestEmail() {
        return guestEmail;
    }

    public void setGuestEmail(String guestEmail) {
        this.guestEmail = guestEmail;
    }

    public String getGuestAddress() {
        return guestAddress;
    }

    public void setGuestAddress(String guestAddress) {
        this.guestAddress = guestAddress;
    }

    public int getInvoiceNumber() {
        return invoiceNumber;
    }

    public void setInvoiceNumber(int invoiceNumber) {
        this.invoiceNumber = invoiceNumber;
    }

    public int getConfirmationNumber() {
        return confirmationNumber;
    }

    public void setConfirmationNumber(int confirmationNumber) {
        this.confirmationNumber = confirmationNumber;
    }

    public String getArrivalDate() {
        return arrivalDate;
    }

    public void setArrivalDate(String arrivalDate) {
        this.arrivalDate = arrivalDate;
    }

    public String getDepartureDate() {
        return departureDate;
    }

    public void setDepartureDate(String departureDate) {
        this.departureDate = departureDate;
    }

    public String getRoomType() {
        return roomType;
    }

    public void setRoomType(String roomType) {
        this.roomType = roomType;
    }

    public String getReference() {
        return reference;
    }

    public void setReference(String reference) {
        this.reference = reference;
    }

    public int getTotalCharge() {
        return totalCharge;
    }

    public void setTotalCharge(int totalCharge) {
        this.totalCharge = totalCharge;
    }
}
public class Room {
    private String stayDate;
    private String item;
    private int quantity;
    private int rate;
    private int amount;

    public String getStayDate() {
        return stayDate;
    }

    public void setStayDate(String stayDate) {
        this.stayDate = stayDate;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int getRate() {
        return rate;
    }

    public void setRate(int rate) {
        this.rate = rate;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }
}