reading specific column of excel into java program

纵饮孤独 提交于 2019-12-12 03:17:28

问题


I need to read specific column of an excel sheet and then declare the variables in java. The program that I have done reads the entire content of excel sheet. But I need to read a fixed column like C.

This is what I have done:

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();
}

}

Here is my excel sheet,

From a bowl of chits numbered /@v1@/ to /@v2@/ , a single chit is randomly drawn. Find the probability that the chit drawn is a number that is a multiple of /@v3@/ or /@ v4@/?

I need to read this data and by matching the pattern /@v1@1, I need to declare the variables. How can I do this?


回答1:


What you can do, you should first get all the columns from the sheet by using sheet.getColumns() and store all columns in a list . Then you can match get all values based on columns. or you can get for only column "C".try using below code. let me know if this works.

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);
    }



回答2:


This is the very simple and efficient code and Working as expected

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();
                }
            }
        }
    }
}



回答3:


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package xlsxreader;

 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
 import org.apache.poi.ss.usermodel.*;

 /**
  *
  * @author khaled
 */
public class XlsxReader {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
    File file = new File("C:\\Users\\khaled\\Desktop\\myXLSX file.xlsx");
    Workbook workbook = WorkbookFactory.create(new FileInputStream(file));
    Sheet sheet = workbook.getSheetAt(0);
    int column_index_1 = 0;
    int column_index_2 = 0;
    int column_index_3 = 0;
    Row row = sheet.getRow(0);
    for (Cell cell : row) {
        // Column header names.
        switch (cell.getStringCellValue()) {
            case "MyFirst Column":
                column_index_1 = cell.getColumnIndex();
                break;
            case "3rd Column":
                column_index_2 = cell.getColumnIndex();
                break;
            case "forth Column":
                column_index_3 = cell.getColumnIndex();
                break;
        }
    }

    for (Row r : sheet) {
        if (r.getRowNum()==0) continue;//hearders
        Cell c_1 = r.getCell(column_index_1);
        Cell c_2 = r.getCell(column_index_2);
        Cell c_3 = r.getCell(column_index_3);
        if (c_1 != null && c_1.getCellType() != Cell.CELL_TYPE_BLANK
                &&c_2 != null && c_2.getCellType() != Cell.CELL_TYPE_BLANK
                &&c_3 != null && c_3.getCellType() != Cell.CELL_TYPE_BLANK) {
            System.out.print("  "+c_1 + "   " + c_2+"   "+c_3+"\n");
        }
    }

}

}



来源:https://stackoverflow.com/questions/27499147/reading-specific-column-of-excel-into-java-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!