java解析excel

//jar包下載地址:http://download.csdn.net/detail/ayearlater/3896587java

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel {
	/**
	 * 讀取Excel文件的內容
	 * 
	 * @param file
	 *            待讀取的文件
	 * @return
	 */
	public static String readExcel(File file) {
		StringBuffer sb = new StringBuffer();

		Workbook wb = null;
		try {
			// 構造Workbook(工做薄)對象
			wb = Workbook.getWorkbook(file);
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (wb == null)
			return null;

		// 得到了Workbook對象以後,就能夠經過它獲得Sheet(工做表)對象了
		Sheet[] sheet = wb.getSheets();

		if (sheet != null && sheet.length > 0) {
			// 對每一個工做表進行循環
			for (int i = 0; i < sheet.length; i++) {
				// 獲得當前工做表的行數
				int rowNum = sheet[i].getRows();
				for (int j = 0; j < rowNum; j++) {
					// 獲得當前行的全部單元格
					Cell[] cells = sheet[i].getRow(j);
					if (cells != null && cells.length > 0) {
						// 對每一個單元格進行循環
						for (int k = 0; k < cells.length; k++) {
							// 讀取當前單元格的值
							String cellValue = cells[k].getContents();
							sb.append(cellValue + "\t");
						}
					}
					sb.append("\r\n");
				}
				sb.append("\r\n");
			}
		}
		// 最後關閉資源,釋放內存
		wb.close();
		return sb.toString();
	}

	public static void main(String[] args) {
		String pathname = "";//放入excel名字
		String str = ReadExcel.readExcel(new File(
				pathname));
		System.out.println(str);
	}
}
相關文章
相關標籤/搜索