OPI jar包 初尝试

来源:互联网 发布:怎么读取串口数据 编辑:程序博客网 时间:2024/05/24 06:48

功能点: 通过 opi jar 包   读取一个excel文件, 将excel文件内容 逐行输出,通过实例进行理解 workbook, sheet  , row , cell 之间的关系。

  

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import com.ab.itws.common.ExcelUtilTest;
import com.ab.itws.common.ExcelUtilReport;

public class test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   ExcelUtilTest a =new ExcelUtilTest();   
   XSSFWorkbook ws= a.getWorkBook("D://abc.xlsx");
   Sheet sheet1 = ws.getSheetAt(0);  // 获得第一表单
   Row   row1   = sheet1.getRow(0);  // 获得第一行
   Cell  cell11 = row1.getCell(0);   // 获得第一行第一列
   System.out.println("第一行第一列的值:" +cell11.getStringCellValue());
   
   //循环 依次取各个cell的数据
   int lastRowNum=sheet1.getLastRowNum(); //获得总行数
   for (int i=0;i<lastRowNum;i++){
    Row   rowi   = sheet1.getRow(i);
    int lastColNum=rowi.getLastCellNum();
    for(int j=0;j<lastColNum;j++){
     Cell cellij=rowi.getCell(j);
     System.out.println("第"+i+"行"+"第"+j+"列值为:"+cellij.getStringCellValue());
    }
   } 
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }

 }
}

 

ExcelUtilTest.java   中 getWorkBook的方法如下:

public static XSSFWorkbook getWorkBook(String filename) throws IOException{  
     XSSFWorkbook workbook=null;  
        if(null!=filename){  
            String fileType=filename.substring(filename.lastIndexOf("."),filename.length());  
            FileInputStream fileStream = new FileInputStream(new File(filename)); 
                workbook = new XSSFWorkbook(fileStream);//创建 Excel 2007 工作簿对象
        }  
        return workbook;  
    }  

0 0
原创粉丝点击