从 Excel 读取数据并传递到 Java 中的 API 请求

问题描述 投票:0回答:1

我有一个 Excel 数据样本,需要读取并以 XML 格式传递给 API。示例:

enter image description here

我尝试使用 Apache POI 按行读取数据。但是我如何获取列名和列中的值并将该数据传递到 API 请求中:

API请求示例:

RequestBody body = RequestBody.create(mediaType, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n<ns2:Fields xmlns:ns2=\"csng\" xmlns:ns1=\"http://www.w3.org/1999/xlink\">\r\n\t<ns2:Field name=\"**Project**\">**customerCloud**</ns2:Field>\r\n\t<ns2:Field name=\"**Product**\">**customerPortal**</ns2:Field>\r\n\t<ns2:Field name=\"**Component**\">**cloudPlatform**</ns2:Field></ns2:Fields>");

Java代码:

File file = new File("testdata.xlsx"); 
    
    FileInputStream inputStream = null;
    
    try {
        inputStream = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    
    workbook = null;
    try {
        workbook = new XSSFWorkbook(inputStream);
        
        rows = workbook.getSheetAt(0).getPhysicalNumberOfRows();
        
        System.out.println("No Of Rows in ExcelSheet---"+rows);
        
        XSSFSheet sheet = workbook.getSheetAt(0);     //creating a Sheet object to retrieve object  
        Iterator<Row> itr = sheet.iterator();    //iterating over excel file  
        
        int i = 0;
        while (itr.hasNext())                 
        {  
            Row rowdata = itr.next();  
            
            Iterator<Cell> cellIterator = rowdata.cellIterator();   //iterating over each column  
            int j=0;
            while (cellIterator.hasNext())   
            {  
                Cell celldata = cellIterator.next();  
                
                System.out.print(celldata.getStringCellValue() + "\n");  
                
                j++;
            
            }
            System.out.println("");  
            i++;
        }
        
    } catch (IOException e) {
        e.printStackTrace();
    }   

使用上面的代码,我得到的输出如下:

Project
Product
Componant

customerCloud
customerPortal
cloudPlatform

如有任何帮助,我们将不胜感激。谢谢

java excel xml apache-poi
1个回答
0
投票

最简单的方法是使用一个库将 Excel 工作表中的表映射到 Java 对象。例如:反射 Excel

您需要创建一个表示表行的类,如下所示:

public class ExcelRow {

    @ExcelColumn("Project")
    private String project;

    @ExcelColumn("Product")
    private String product;

    @ExcelColumn("Componant")
    private String component;
}

然后您可以读取行并检索每列的值:

List<ExcelRow> excelRows = new ReflectiveExcelReader(yourFile).readRows(ExcelRow.class);
© www.soinside.com 2019 - 2024. All rights reserved.