将excel的特定列读入java程序

时间:2014-12-16 06:56:09

标签: java excel jxl

我需要读取excel表的特定列,然后在java中声明变量。我完成的程序读取了excel表的全部内容。但是我需要读一个像C这样的固定列。

这就是我所做的:

import java.io.File;
import java.io.IOException;
import jxl.Cell; 
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class JavaApplication4 
{

private String inputFile;
String[][] data = null;
public void setInputFile(String inputFile) 
{
    this.inputFile = inputFile;
}

public String[][] read() throws IOException  
{
    File inputWorkbook = new File(inputFile);
    Workbook w;

    try 
    {
        w = Workbook.getWorkbook(inputWorkbook);
        // Get the first sheet


        Sheet sheet = w.getSheet(0);
        data = new String[sheet.getColumns()][sheet.getRows()];
        // Loop over first 10 column and lines
   //     System.out.println(sheet.getColumns() +  " " +sheet.getRows());
        for (int j = 0; j <sheet.getColumns(); j++) 
        {
            for (int i = 0; i < sheet.getRows(); i++) 
            {
                Cell cell = sheet.getCell(j, i);
                data[j][i] = cell.getContents();
              //  System.out.println(cell.getContents());
            }
        }

       for (int j = 0; j < data.length; j++) 
        {
            for (int i = 0; i <data[j].length; i++) 
            {

                System.out.println(data[j][i]);
            }
        } 

    } 

    catch (BiffException e) 
    {
        e.printStackTrace();
    }
return data;
}

public static void main(String[] args) throws IOException 
{
    JavaApplication4 test = new JavaApplication4();
    test.setInputFile("C://users/admin/Desktop/Content.xls");
    test.read();
}

}

这是我的Excel表格,

从一碗编号为/@v1@//@v2@/的chits,随机抽取一个小块。找出所绘制的chit是/@v3@//@ v4@/倍数的数字的概率?

我需要读取这些数据,并通过匹配模式/@v1@1,我需要声明变量。我怎么能这样做?

4 个答案:

答案 0 :(得分:1)

您可以做什么,首先应使用sheet.getColumns()获取工作表中的所有列,并将所有列存储在列表中。然后,您可以根据列匹配获取所有值。或者您只能使用下面的代码来获取#34; C&#34; .try。如果有效,请告诉我。

int masterSheetColumnIndex = sheet.getColumns();
    List<String> ExpectedColumns = new ArrayList<String>();
    for (int x = 0; x < masterSheetColumnIndex; x++) {
        Cell celll = sheet.getCell(x, 0);
        String d = celll.getContents();
        ExpectedColumns.add(d);
    }
    LinkedHashMap<String, List<String>> columnDataValues = new LinkedHashMap<String, List<String>>();

    List<String> column1 = new ArrayList<String>();
    // read values from driver sheet for each column
    for (int j = 0; j < masterSheetColumnIndex; j++) {
        column1 = new ArrayList<String>();
        for (int i = 1; i < sheet.getRows(); i++) {
            Cell cell = sheet.getCell(j, i);
            column1.add(cell.getContents());
        }
        columnDataValues.put(ExpectedColumns.get(j), column1);
    }

答案 1 :(得分:0)

这是非常简单有效的代码,按预期工作

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class TestExcelFile {

    public static void main(String[] args) {
        String envFilePath = System.getenv("AZURE_FILE_PATH");

        // upload list of files/directory to blob storage
        File folder = new File(envFilePath);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                System.out.println("File " + listOfFiles[i].getName());

                Workbook workbook;
                //int masterSheetColumnIndex = 0;
                try {
                        workbook = WorkbookFactory.create(new FileInputStream(envFilePath + "\\"+ listOfFiles[i].getName()));
                    // Get the first sheet.
                    Sheet sheet = workbook.getSheetAt(0);

                    //we will search for column index containing string "Your Column Name" in the row 0 (which is first row of a worksheet
                    String columnWanted = "Column_Name";
                    Integer columnNo = null;
                    //output all not null values to the list
                    List<Cell> cells = new ArrayList<Cell>();

                    // Get the first cell.
                    Row row = sheet.getRow(0);
                    //Cell cell = row.getCell(0);
                    for (Cell cell : row) {
                        // Column header names.
                        //System.out.println(cell.toString());  
                        if (cell.getStringCellValue().equals(columnWanted)){
                            columnNo = cell.getColumnIndex();
                        }
                    }

                    if (columnNo != null){
                        for (Row row1 : sheet) {
                           Cell c = row1.getCell(columnNo);
                           if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
                              // Nothing in the cell in this row, skip it
                           } else {
                              cells.add(c);
                              //System.out.println(c);
                           }
                        }

                    }else{
                        System.out.println("could not find column " + columnWanted + " in first row of " + listOfFiles[i].getName());
                    }

                } catch (InvalidFormatException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

答案 2 :(得分:0)

XLSX_File

 public class MoviesViewModel
{
    public Movies mvz { get; set; }
    public List<Actors> act { get; set; }
    public MoviesViewModel()
    {
        mvz = new Movies();
        act = new List<Actors>();
    }
}

}

OutPut

答案 3 :(得分:0)

从Excel文件中读取特定列

screenshot of the excel i am using,column 1-ppm,sheet at 0th position-Year

    File myFile = new File(path);
    FileInputStream fis = new FileInputStream(myFile);

    // Finds the workbook instance for XLSX file
    XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);

    //XSSFWorkbook workBook = new XSSFWorkbook();
    //Reading sheet at number 0 in spreadsheet(image attached for reference
    Sheet sheet = myWorkBook.getSheetAt(0);

    //creating a Sheet object to retrieve object  
    Iterator<Row> itr = sheet.iterator();//iterating over excel file  

    while (itr.hasNext())                 
    {  
        Row row = itr.next();
        Iterator<Cell> cellIterator = row.cellIterator();//iterating over each column
        //Reading cell in my case column name is ppm
        Cell ppmEx= row.getCell(0);

        //Cell cell = cellIterator.next();
        while (cellIterator.hasNext())
        {  
            Cell cell = cellIterator.next();
            //Check the cell type and format accordingly
            switch (cell.getCellType()) 
            {
                case Cell.CELL_TYPE_NUMERIC:
                    //System.out.println(cell.getNumericCellValue() + "    ");
                    al.add(cell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:
                    //System.out.println(cell.getStringCellValue()+" ");
                    al.add(cell.getStringCellValue());
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    //System.out.println(cell.getBooleanCellValue()+" ");
                    al.add(cell.getBooleanCellValue());
                case Cell.CELL_TYPE_BLANK:
                    //System.out.println("blank");
                    al.add("blank");

            }  
        }  
        System.out.println("-");
    }