Apache POI를 사용하여 특정 Excel 열을 읽는 방법
Apache POI 사용 중 Excel에 문제가 있습니다.여러 행으로 읽을 수 있지만 특정 열만 읽고 싶은 상황이 발생할 수 있습니다.
그래서 'A' 열만 읽거나 'C' 열만 읽으면 됩니다.
자바 언어를 사용하고 있습니다.
heikkim이 옳습니다.여기 제가 가지고 있는 코드 중 몇 가지 샘플 코드가 있습니다.
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
...
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
row = sheet.getRow(rowIndex);
if (row != null) {
Cell cell = row.getCell(colIndex);
if (cell != null) {
// Found column and there is value in the cell.
cellValueMaybeNull = cell.getStringCellValue();
// Do something with the cellValueMaybeNull here ...
// break; ???
}
}
}
를 위해colCount같은 것을 사용하다row.getPhysicalNumberOfCells()
Sheet sheet = workBook.getSheetAt(0); // Get Your Sheet.
for (Row row : sheet) { // For each Row.
Cell cell = row.getCell(0); // Get the Cell at the Index / Column you want.
}
내 해결책은 좀 더 간단한 코드와이즈야.
좋아, 네 질문에서 넌 단지 특정 칼럼을 읽고 싶을 뿐이야.따라서 행에서 반복한 후 해당 셀에서 반복할 때 열의 인덱스를 간단히 확인할 수 있습니다.
Iterator<Row> rowIterator = mySheet.iterator(); // Traversing over each row of XLSX file
while (rowIterator.hasNext()) {
Row row = rowIterator.next(); // For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
println "column index"+cell.getColumnIndex()//You will have your columns fixed in Excel file
if(cell.getColumnIndex()==3)//for example of c
{
print "done"
}
}
}
POI 3.12를 사용하고 있습니다. org.apache.poi:poi:3.12' 도움이 되길 바랍니다.건배!
행을 반복하여 각 행에서 동일한 셀을 읽을 수 있습니다(이것은 열을 구성하지 않습니까?).
import java.io.*;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.*;
import java.text.*;
public class XSLXReader {
static DecimalFormat df = new DecimalFormat("#####0");
public static void main(String[] args) {
FileWriter fostream;
PrintWriter out = null;
String strOutputPath = "H:\\BLR_Team\\Kavitha\\Excel-to-xml\\";
String strFilePrefix = "Master_5.2-B";
try {
InputStream inputStream = new FileInputStream(new File("H:\\BLR_Team\\Kavitha\\Excel-to-xml\\Stack-up 20L pure storage 11-0039-01 ISU_USA-A 1-30-17-Rev_exm.xls"));
Workbook wb = WorkbookFactory.create(inputStream);
// Sheet sheet = wb.getSheet(0);
Sheet sheet =null;
Integer noOfSheets= wb.getNumberOfSheets();
for(int i=0;i<noOfSheets;i++){
sheet = wb.getSheetAt(i);
System.out.println("Sheet : "+i + " " + sheet.getSheetName());
System.out.println("Sheet : "+i + " " + sheet.getFirstRowNum());
System.out.println("Sheet : "+i + " " + sheet.getLastRowNum());
//Column 29
fostream = new FileWriter(strOutputPath + "\\" + strFilePrefix+i+ ".xml");
out = new PrintWriter(new BufferedWriter(fostream));
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<Bin-code>");
boolean firstRow = true;
for (Row row : sheet) {
if (firstRow == true) {
firstRow = false;
continue;
}
out.println("\t<DCT>");
out.println(formatElement("\t\t", "ID", formatCell(row.getCell(0))));
out.println(formatElement("\t\t", "Table_name", formatCell(row.getCell(1))));
out.println(formatElement("\t\t", "isProddaten", formatCell(row.getCell(2))));
out.println(formatElement("\t\t", "isR3P01Data", formatCell(row.getCell(3))));
out.println(formatElement("\t\t", "LayerNo", formatCell(row.getCell(29))));
out.println("\t</DCT>");
}
CellReference ref = new CellReference("A13");
Row r = sheet.getRow(ref.getRow());
if (r != null) {
Cell c = r.getCell(ref.getCol());
System.out.println(c.getRichStringCellValue().getString());
}
for (Row row : sheet) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK:
System.out.println();
break;
default:
System.out.println();
}
}
}
out.write("</Bin-code>");
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String formatCell(Cell cell)
{
if (cell == null) {
return "";
}
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
return "";
case Cell.CELL_TYPE_BOOLEAN:
return Boolean.toString(cell.getBooleanCellValue());
case Cell.CELL_TYPE_ERROR:
return "*error*";
case Cell.CELL_TYPE_NUMERIC:
return XSLXReader.df.format(cell.getNumericCellValue());
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
default:
return "<unknown value>";
}
}
private static String formatElement(String prefix, String tag, String value) {
StringBuilder sb = new StringBuilder(prefix);
sb.append("<");
sb.append(tag);
if (value != null && value.length() > 0) {
sb.append(">");
sb.append(value);
sb.append("</");
sb.append(tag);
sb.append(">");
} else {
sb.append("/>");
}
return sb.toString();
}
}
이 코드는 다음 3가지 작업을 수행합니다.
- Excel to XML 파일 생성.영어 이름은 김동
- 특정 셀의 내용을 인쇄합니다.A13
- 또한 Excel 콘텐츠를 일반 텍스트 형식으로 인쇄합니다.Import하는 자: poi-3.9.jar, poi-oxml-3.9.jar, poi-oxml-schemas-3.9.jar, xbean-2.3.0.jar, xml-beans-xml public-2.4.0.jar, dom4j-1.5.jar.jar.jar.jar
엑셀데이터를열별로읽을수있는코드입니다.
public ArrayList<String> extractExcelContentByColumnIndex(int columnIndex){
ArrayList<String> columndata = null;
try {
File f = new File("sample.xlsx")
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > 0){ //To filter column headings
if(cell.getColumnIndex() == columnIndex){// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(columndata);
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
행 셀 반복기를 사용하여 열을 반복한다는 점에 유의하십시오(Iterator<Cell> cellIterator = row.cellIterator();)는 열을 자동으로 건너뛸 수 있습니다.나는 방금 그러한 행동을 폭로하는 문서를 접했다.
for 루프의 인덱스 사용 및 사용 반복row.getCell(i)열을 건너뛰지 않고 올바른 열 인덱스의 값을 반환했습니다.
언급URL : https://stackoverflow.com/questions/12857469/using-apache-poi-how-to-read-a-specific-excel-column
'programing' 카테고리의 다른 글
| '프로젝트 이름'이 최적화로 컴파일되었습니다.스텝 동작이 이상할 수 있습니다.변수를 사용할 수 없습니다. (0) | 2023.04.16 |
|---|---|
| 값 '1'을 반환합니다. 참조된 셀이 비어 있습니다. (0) | 2023.04.16 |
| 윈도우즈 cmd 스크립트에서 여러 명령 실행 (0) | 2023.04.16 |
| npm ERR!오류: EPERM: 작업이 허용되지 않습니다. 이름을 변경하십시오. (0) | 2023.04.16 |
| Objective-C 내에서 Swift 클래스를 사용할 수 없습니다. (0) | 2023.04.16 |