首页 文章

Apache POI - JAVA - 迭代excel中的列

提问于
浏览
2

这里是java的新手 . 我正在编写一个代码来读取excel文件(查看列中的单元格),然后编写类似下表的内容:

我有一个excel文件,如下所示:

col1     col2    col3    col4
      -----------------------------
row1 | 2,3,1    _        1      w
row2 | 3,2,7    _        2      x
row3 |   _      _        3      y
row4 |  4,9     _        4      z

我在第2列中写了一些值(使用XLWT),如下所示:

col1     col2    col3    col4
      -----------------------------
row1 | 2,3,1  x,y,w      1      w
row2 | 3,2,7   y,x       2      x
row3 |   _      _        3      y
row4 |  4,9     z        4      z

基本上,正在比较第3列和第1列,如果单元格(1,1)在第3列中具有匹配的值,则将第4列的值(对应于第3列)写入第2列 .

我实际上是用Python完成的,我考虑使用Jython,但是,我找不到任何关于将python模块导入Jython代码的文档 . 我相信XSSF apache-poi是我在java中处理xlsx文件的唯一方法 .

相关页面:How to do cell iteration of excel in java

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

public class Python {
    public static void main(String[] args) {
        try {


        FileInputStream file = new FileInputStream(new File("C:\\Users\\...\\Bioactives25s.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet worksheet = workbook.getSheetAt(0);
        for (int i = 0; i < 9999; i++) { 
            XSSFRow row = worksheet.getRow(i);
            if(row == null) {
                //iterates over rows
            }


        for (int j = 0; j < 30; j++) {
             XSSFCell cell = row.getCell(j);

                if(cell == null) {
               //iterates over cells

主要是寻找迭代列值的方法 . 我查看了文档:http://poi.apache.org/spreadsheet/quick-guide.html#Iterator

但我只能找到处理行和单元格的代码,而不是列 . 我想迭代列 . 有没有代码可以解决这个问题?

1 回答

  • 3

    只需遍历行并获取所需的单元格:

    int columnIndex = 3;
    for (int rowIndex = 0; rowIndex<3; rowIndex++){
        Row row = CellUtil.getRow(rowIndex, sheet);
        Cell cell = CellUtil.getCell(row, columnIndex);
    }
    

相关问题