java讀取Excel的方法,解析xlsx(內含所需jar包)

package com.jiwu.struts.action.hui;

import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class demo {
	public static void main(String[] args) {
		try {
			String bid="";
			String phone="";
			InputStream is = new FileInputStream("E:/1.xlsx");
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
			// 獲取每一個工作薄
			for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
				XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
				if (xssfSheet == null) {
					continue;
				}
				// 獲取當前工作薄的每一行
				for (int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
					XSSFRow xssfRow = xssfSheet.getRow(rowNum);
					if (xssfRow != null) {
						// 讀取第一列數據
						XSSFCell one = xssfRow.getCell(0);
						bid+=getValue(one)+",";
						// 讀取第二列數據
						XSSFCell two = xssfRow.getCell(1);
						phone+=getValue(two)+",";
//						XSSFCell three = xssfRow.getCell(2);
						// 讀取第三列數據
						// 需要轉換數據的話直接調用getValue獲取字符串
					}
				}
				break;
			}
			System.out.println(bid+","+phone);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 轉換數據格式
	private static String getValue(XSSFCell xssfRow) {

		if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
			return String.valueOf(xssfRow.getBooleanCellValue());
		} else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
			return String.valueOf(xssfRow.getNumericCellValue());
		} else {
			return String.valueOf(xssfRow.getStringCellValue());
		}
	}
}



jar包地址   鏈接: https://pan.baidu.com/s/1c3oVVws 密碼: jpui

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章