Iterate over rows and cells(EXCEL文件的读取)_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Iterate over rows and cells(EXCEL文件的读取)

Iterate over rows and cells(EXCEL文件的读取)

 2013/9/13 15:52:40  宋建勇  程序员俱乐部  我要评论(0)
  • 摘要:BusyDevelopers'GuidetoHSSFandXSSFFeatures/***ReadLine.java*cn.com.songjy.test.excel*Function:TODO**versiondateauthor*──────────────────────────────────*1.02013-9-12songjy**Copyright(c)2013,TNTAllRightsReserved.*/packagecn.com.songjy.test.excel
  • 标签:excel 文件
Busy Developers' Guide to HSSF and XSSF Features

class="java" name="code">/**
 * ReadLine.java
 * cn.com.songjy.test.excel
 * Function: TODO 
 *
 *   version    date      author
 * ──────────────────────────────────
 *   	1.0	 2013-9-12    songjy
 *
 * Copyright (c) 2013, TNT All Rights Reserved.
 */

package cn.com.songjy.test.excel;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.ss.util.CellReference;

/**
 * ClassName:ReadLine
 * 
 * @author songjy
 * @version 1.0
 * @since v1.0
 * @Date 2013-9-12 下午7:48:22
 */

public class ReadLine {

	private Log log = LogFactory.getLog(ReadLine.class);

	public void read(String excel_file_path) throws IOException {
		InputStream inp = new FileInputStream(excel_file_path);
		Workbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
		Sheet sheet = wb.getSheetAt(0);
		for (Row row : sheet) {
			DecimalFormat df = new DecimalFormat("0");
			for (Cell cell : row) {
				/*读取10行4列数据*/
				if(cell.getColumnIndex()>3) continue;//只读取4列
				if(row.getRowNum()>9) break;//只读取10行
				CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
				log.info(cellRef.formatAsString());
				log.info(" - ");

				switch (cell.getCellType()) {
				case Cell.CELL_TYPE_STRING:
					log.info(cell.getRichStringCellValue().getString());
					break;
				case Cell.CELL_TYPE_NUMERIC:
					if (DateUtil.isCellDateFormatted(cell)) {
						log.info(cell.getDateCellValue());
					} else {
						log.info(df.format(cell.getNumericCellValue()));
					}
					break;
				case Cell.CELL_TYPE_BOOLEAN:
					log.info(cell.getBooleanCellValue());
					break;
				case Cell.CELL_TYPE_FORMULA:
					log.info(cell.getCellFormula());
					break;
				default:
					log.info("----");
				}
			}
		}
	}

	public static void main(String[] args) {
		try {
			new ReadLine().read("山西电信二次放号比对.xls");
		} catch (IOException e) {

			e.printStackTrace();

		}
	}
}
发表评论
用户名: 匿名