读写Excel

 

  公司需要处理一些Excel文件数据。懒,搜索了以下读取方法.

  忘记出自网络上那里的了、

 

  记录下来,以后可以学习学习,需要导入jar包 poi-3.6-20091214.jar等,所需jar包在后面下载

 

  1、读取Excel

 

public class ReadExcel {

    public static void main(String[]args){  
        
       ArrayList<String> columnList = new ArrayList<String>();  
       File file = new File("E:\\test.xls");  
     
       try {  
	      FileInputStream in = new FileInputStream(file);  
	     
	      HSSFWorkbook wb = new HSSFWorkbook(in);  
	     
	      Sheet sheet = wb.getSheetAt(0);  
	      int firstRowNum = sheet.getFirstRowNum();  
	      int lastRowNum = sheet.getLastRowNum();  
	      
	      Row row = null;  
	      Cell cell_a = null;  
	      for (int i = firstRowNum; i <= lastRowNum; i++) {  
		       row = sheet.getRow(i);          //取得第i行
		       if(row!=null){
		    	   cell_a = row.getCell(4);        //取得i行的第4列  
		    	   if(cell_a!=null){
		    		   String cellValue = cell_a.getCellType()+"";
		    		   columnList.add(cellValue);  
		    	   }
		       }
		  }  
	    }catch (Exception e) {  
	        e.printStackTrace();  
	    }  
	}
	     
} 

 

 

2、写入Excel

 

 

public class WriteExcel {

	public static void main(String[] args) {
		Workbook workbook = null;
		Sheet sheet = null;
		
		try {
			OutputStream out = new FileOutputStream("E:\\test.xls");
			workbook = new HSSFWorkbook();
			sheet = workbook.createSheet("testWrite");
			Row row = null;
			Cell cell = null;
			
			for(int i=0;i<6;i++){
				row = sheet.createRow(i);
				for(int j = 0;j<6;j++){
					cell = row.createCell(j);
					sheet.setColumnWidth(j, 4500);
					cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
					cell.setCellValue((i+j)%2==0 ? true : false);
				}
			}
			workbook.write(out);
			if(out!=null) out.flush();
			if(out!=null) out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值