package poi;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelReadDemo {
public static void main(String[] args) throws IOException {
excel2003("C:/Users/lastone/Desktop/test.xls");
//excelX("C:/Users/lastone/Desktop/test.xlsx");
}
/**
* 支持 Excel2003、2007
*@Title: excelX
*@Description:
*@添加时间:2014-7-21
*@author : fdcxy
*/
public static void excelX(String fStr) throws IOException {
FileInputStream fis = new FileInputStream( fStr );
String ext = fStr.substring(fStr.lastIndexOf('.')+1);
Workbook wb = null;
Sheet sheet = null;
//得到Excel工作簿对象
if("xls".equals(ext))
wb = new HSSFWorkbook(fis);
else if("xlsx".equals(ext))
wb = new XSSFWorkbook(fis);
//得到Excel工作表对象
sheet = wb.getSheetAt(0);
int rowStartNum = (sheet.getFirstRowNum());
int rowEndNum = (sheet.getLastRowNum()+1);
for(int i=rowStartNum;i<rowEndNum;i++){
//得到Excel工作表的行
Row row = sheet.getRow(i);
System.out.print((i+1)+"\t");//行标
int firstNum = row.getFirstCellNum();
int endNum = row.getLastCellNum();
for(int j=firstNum;j<endNum;j++){
//得到Excel工作表指定行的单元格
Cell cell = row.getCell(j);
//CellStyle cellStyle = cell.getCellStyle();//得到单元格样式
if(cell!=null){
//内容格式
if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC)
System.out.print(cell.getNumericCellValue()+"\t");
else if(cell.getCellType()==Cell.CELL_TYPE_STRING)
System.out.print(cell.getStringCellValue()+"\t");
}
}
System.out.println();
}
System.out.println("rows:"+rowEndNum+"行");
}
/**
* 支持 Excel2003
*@Title: excel2003
*@Description:
*@添加时间:2014-7-21
*@author : fdcxy
*/
public static void excel2003(String fStr) throws IOException {
FileInputStream fis = new FileInputStream( fStr );
//得到Excel工作簿对象
HSSFWorkbook wb = new HSSFWorkbook(fis);
//得到Excel工作表对象
HSSFSheet sheet = wb.getSheetAt(0);
int rowStartNum = (sheet.getFirstRowNum());
int rowEndNum = (sheet.getLastRowNum()+1);
for(int i=rowStartNum;i<rowEndNum;i++){
//得到Excel工作表的行
HSSFRow row = sheet.getRow(i);
System.out.print((i+1)+"\t");//行标
int firstNum = row.getFirstCellNum();
int endNum = row.getLastCellNum();
for(int j=firstNum;j<endNum;j++){
//得到Excel工作表指定行的单元格
HSSFCell cell = row.getCell(j);
//CellStyle cellStyle = cell.getCellStyle();//得到单元格样式
if(cell!=null){
if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC)
System.out.print(cell.getNumericCellValue()+"\t");
else if(cell.getCellType()==Cell.CELL_TYPE_STRING)
System.out.print(cell.getStringCellValue()+"\t");
}
}
System.out.println();
}
System.out.println("rows:"+rowEndNum+"行");
}
}
POI 读取Excel2003、2007的一个Demo
最新推荐文章于 2024-04-23 17:13:16 发布