需要使用Java代码检索列表中的所有Excel列名

时间:2012-10-09 12:46:03

标签: java xml tibco

我需要从excel文件中获取所有列名,并且在java代码的帮助下它可以是.xls或.xlsx。 我将提供文件名和文件目录作为输入,代码需要读取目录中的文件并捕获列表中的所有列并以xml格式发送输出。

以下是示例xml数据,其列数将多于下面的

Location ID Location Name   Product ID  Supplier Name   
Invoice Number  Sales Qty   Buy Qty Inventory Qty

2-LG2-344   ABC BBC CBC AK1234  5   4   3

2-LG2-344   ABC CBC CBC AK1235  2   6   5

2-LG2-344   ABC DBC CBC AK1236  3   2   3



the output should be like 
<ptnr_label_names>
<field_name>Location ID<field_name>
<field_name>Location Name<field_name>
<field_name>Product ID<field_name>
<field_name>Supplier Name<field_name>
<field_name>Invoice Number<field_name>
<field_name>Sales Qty<field_name>
<field_name>Buy Qty<field_name>
<field_name>Inventory Qty<field_name>
</ptnr_label_names>

4 个答案:

答案 0 :(得分:2)

您可以使用Apache POI。一个简单的代码看起来像这样:

        FileInputStream fis = new FileInputStream("test.xls");
        Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("test.xls")
        Sheet sheet = wb.getSheetAt(0);
        Row row = sheet.getRow(0); //assume first row is column header row
        System.out.println("<ptnr_label_names>");
        for(int col=0; col< numXolumns; col++){
           Cell cell = row.getCell(col);
           String columnName = cell.getStringCellValue();
           System.out.println("<field_name> "+columnName +"</field_name>");
       }
        System.out.println("</ptnr_label_names>");

答案 1 :(得分:0)

在excel文件中找到列名所在的行 然后通过从一列移动到另一列来读取单元格。

    Row row=sheet.getRow(r);//r is the row number for your column names
    Cell cell=row.getCell(c);//c is the column number 

您需要通过更改上述代码中c的值来迭代每列。

答案 2 :(得分:0)

祝你好运:)

答案 3 :(得分:0)

如果我读得正确: “excel文件中的所有列名称都可以是.xls”

我已根据要求附加了列表中包含列ID的excel fiel。 但是,由于excel的限制,无法使用这些创建自定义列表。

Excel ColumnID