[java]源码详解java读取excel内容
本例主要讲解通过java程序打印出excel文件中内容。直接贴源码,然后再整理原理:
[java]
package dec;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
*
* <p>
* Title: JAVA读取Excel测试代码
* </p>
*
* <p>
* Description: 示例 业务类
* </p>
*
* <p>
* Copyright: Copyright (c) 2012
* </p>
*
*
* @author dml@2012-12-10
* @version 1.0
*/
public class ExcelReader {
private HSSFWorkbook wb = null;// book [includes sheet]
private HSSFSheet sheet = null;
private HSSFRow row = null;
private int sheetNum = 0; // 第sheetnum个工作表
private int rowNum = 0;
private FileInputStream fis = null;
private File file = null;
public ExcelReader() {
}
public ExcelReader(File file) {
this.file = file;
}
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
public void setSheetNum(int sheetNum) {
this.sheetNum = sheetNum;
}
public void setFile(File file) {
this.file = file;
}
/**
* 读取excel文件获得HSSFWorkbook对象
*/
public void open() throws IOException {
fis = new FileInputStream(file);
wb = new HSSFWorkbook(new POIFSFileSystem(fis));
fis.close();
}
/**
* 返回sheet表数目
*
* @return int
*/
public int getSheetCount() {
int sheetCount = -1;
sheetCount = wb.getNumberOfSheets();
return sheetCount;
}
/**
* sheetNum下的记录行数
*
* @return int
*/
public int getRowCount() {
if (wb == null)
System.out.println("=============WorkBook为空==============");
HSSFSheet sheet = wb.getSheetAt(this.sheetNum);
int rowCount = -1;
rowCount = sheet.getLastRowNum();
return rowCount;
}
/**
* 读取指定sheetNum的rowCount
*
* @param sheetNum
* @return int
*/
public int getRowCount(int sheetNum) {
HSSFSheet sheet = wb.getSheetAt(sheetNum);
int rowCount = -1;
rowCount = sheet.getLastRowNum();
return rowCount;
}
/**
* 得到指定行的内容
*
* @param lineNum
* @return String[]
*/
public String[] readExcelLine(int lineNum) {
return readExcelLine(this.sheetNum, lineNum);
}
/**
* 指定工作表和行数的内容
*
* @param sheetNum
* @param lineNum
* @return String[]
*/
public String[] readExcelLine(int sheetNum, int lineNum) {
if (sheetNum < 0 || lineNum < 0)
return null;
String[] strExcelLine = null;
try {
sheet = wb.getSheetAt(sheetNum);
row = sheet.getRow(lineNum);
int cellCount = row.getLastCellNum();
strExcelLine = new String[cellCount + 1];
for (int i = 0; i <= cellCount; i++) {
strExcelLine[i] = readStringExcelCell(lineNum, i);
}
} catch (Exception e) {
e.printStackTrace();
}
return strExcelLine;
}
/**
* 读取指定列的内容
*
* @param cellNum
* @return String
*/
public String readStringExcelCell(int cellNum) {
return readStringExcelCell(this.rowNum, cellNum);
}
补充:软件开发 , Java ,