Java讀取Excel(包括2003和2007)

package com.liberty.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 可以從 http://poi.apache.org/ 這裏下載到 POI 的 jar 包 POI 創建和讀取 2003-2007 版本 Excel 文件
 */
public class CreatAndReadExcel {
	public static void main(String[] args) throws Exception {
		creat2003Excel();// 創建2007版Excel文件
		creat2007Excel();// 創建2003版Excel文件
		// 讀取2003Excel文件
		String path2003 = System.getProperty("user.dir") + System.getProperty("file.separator") + "style_2003.xls";// 獲取項目文件路徑+2003版文件名
		System.out.println("路徑:" + path2003);
		File f2003 = new File(path2003);
		try {
			readExcel(f2003);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 讀取2007Excel文件
		String path2007 = System.getProperty("user.dir") + System.getProperty("file.separator") + "style_2007.xlsx";// 獲取項目文件路徑+2007版文件名
		System.out.println("路徑:" + path2007);
		File f2007 = new File(path2007);
		try {
			readExcel(f2007);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 創建 2007 版 Excel 文件
	 * 
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static void creat2007Excel() throws FileNotFoundException, IOException {
		// HSSFWorkbook workBook = new HSSFWorkbook();// 創建一個excel文檔對象
		XSSFWorkbook workBook = new XSSFWorkbook();
		XSSFSheet sheet = workBook.createSheet();// 創建一個工作薄對象
		sheet.setColumnWidth(1, 10000);// 設置第二列的寬度爲
		XSSFRow row = sheet.createRow(1);// 創建一個行對象
		row.setHeightInPoints(23);// 設置行高23像素
		XSSFCellStyle style = workBook.createCellStyle();// 創建樣式對象
		// 設置字體
		XSSFFont font = workBook.createFont();// 創建字體對象
		font.setFontHeightInPoints((short) 15);// 設置字體大小
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 設置粗體
		font.setFontName("黑體");// 設置爲黑體字
		style.setFont(font);// 將字體加入到樣式對象
		// 設置對齊方式
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
		// 設置邊框
		style.setBorderTop(HSSFCellStyle.BORDER_THICK);// 頂部邊框粗線
		style.setTopBorderColor(HSSFColor.RED.index);// 設置爲紅色
		style.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);// 底部邊框雙線
		style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);// 左邊邊框
		style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);// 右邊邊框
		// 格式化日期
		style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
		XSSFCell cell = row.createCell(1);// 創建單元格
		cell.setCellValue(new Date());// 寫入當前日期
		cell.setCellStyle(style);// 應用樣式對象
		// 文件輸出流
		FileOutputStream os = new FileOutputStream("style_2007.xlsx");
		workBook.write(os);// 將文檔對象寫入文件輸出流
		os.close();// 關閉文件輸出流
		System.out.println("創建成功office 2007 excel");
	}

	/**
	 * 創建 2003 版本的 Excel 文件
	 */
	private static void creat2003Excel() throws FileNotFoundException, IOException {
		HSSFWorkbook workBook = new HSSFWorkbook();// 創建一個excel文檔對象
		HSSFSheet sheet = workBook.createSheet();// 創建一個工作薄對象
		sheet.setColumnWidth(1, 10000);// 設置第二列的寬度爲
		HSSFRow row = sheet.createRow(1);// 創建一個行對象
		row.setHeightInPoints(23);// 設置行高23像素
		HSSFCellStyle style = workBook.createCellStyle();// 創建樣式對象
		// 設置字體
		HSSFFont font = workBook.createFont();// 創建字體對象
		font.setFontHeightInPoints((short) 15);// 設置字體大小
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 設置粗體
		font.setFontName("黑體");// 設置爲黑體字
		style.setFont(font);// 將字體加入到樣式對象
		// 設置對齊方式
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
		// 設置邊框
		style.setBorderTop(HSSFCellStyle.BORDER_THICK);// 頂部邊框粗線
		style.setTopBorderColor(HSSFColor.RED.index);// 設置爲紅色
		style.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);// 底部邊框雙線
		style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);// 左邊邊框
		style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);// 右邊邊框
		// 格式化日期
		style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
		HSSFCell cell = row.createCell(1);// 創建單元格
		cell.setCellValue(new Date());// 寫入當前日期
		cell.setCellStyle(style);// 應用樣式對象
		// 文件輸出流
		FileOutputStream os = new FileOutputStream("style_2003.xls");
		workBook.write(os);// 將文檔對象寫入文件輸出流
		os.close();// 關閉文件輸出流
		System.out.println("創建成功office 2003 excel");
	}

	/**
	 * 對外提供讀取 excel 的方法
	 */
	public static List<List<Object>> readExcel(File file) throws IOException {
		String fileName = file.getName();
		String extension = fileName.lastIndexOf(".") == -1 ? " " : fileName.substring(fileName.lastIndexOf(".") + 1);
		if ("xls".equals(extension)) {
			return read2003Excel(file);
		} else if ("xlsx".equals(extension)) {
			return read2007Excel(file);
		} else {
			throw new IOException("不支持的文件類型");
		}
	}

	/**
	 * 讀取office 2003 excel
	 * 
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	private static List<List<Object>> read2003Excel(File file) throws IOException {
		List<List<Object>> list = new LinkedList<List<Object>>();
		HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
		HSSFSheet sheet = hwb.getSheetAt(0);
		Object value = null;
		HSSFRow row = null;
		HSSFCell cell = null;
		System.out.println("讀取office 2003 excel內容如下:");
		for (int i = sheet.getFirstRowNum(); i <= sheet.getPhysicalNumberOfRows(); i++) {
			row = sheet.getRow(i);
			if (row == null) {
				continue;
			}
			List<Object> linked = new LinkedList<Object>();
			for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
				cell = row.getCell(j);
				if (cell == null) {
					continue;
				}
				DecimalFormat df = new DecimalFormat("0");// 格式化number String
				// 字符
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
				DecimalFormat nf = new DecimalFormat("0.00");// 格式化數字
				switch (cell.getCellType()) {
				case XSSFCell.CELL_TYPE_STRING:
					// System.out.println(i + "行" + j + "列is String type");
					value = cell.getStringCellValue();
					System.out.print(" " + value + " ");
					break;
				case XSSFCell.CELL_TYPE_NUMERIC:
					// System.out.println(i + "行" + j
					// + "列is Number type DateFormt:"
					// + cell.getCellStyle().getDataFormatString());
					if ("@".equals(cell.getCellStyle().getDataFormatString())) {
						value = df.format(cell.getNumericCellValue());
					} else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
						value = nf.format(cell.getNumericCellValue());
					} else {
						value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
					}
					System.out.print(" " + value + " ");
					break;
				case XSSFCell.CELL_TYPE_BOOLEAN:
					// System.out.println(i + "行" + j + "列is Boolean type");
					value = cell.getBooleanCellValue();
					System.out.print(" " + value + " ");
					break;
				case XSSFCell.CELL_TYPE_BLANK:
					// System.out.println(i + "行" + j + "列is Blank type");
					value = " ";
					System.out.print(" " + value + " ");
					break;
				default:
					// System.out.println(i + "行" + j + "列is default type");
					value = cell.toString();
					System.out.print(" " + value + " ");
				}
				if (value == null || " ".equals(value)) {
					continue;
				}
				linked.add(value);
			}
			System.out.println(" ");
			list.add(linked);
		}
		return list;
	}

	/**
	 * 讀取Office 2007 excel 
	 */
	private static List<List<Object>> read2007Excel(File file) throws IOException { 
		List<List<Object>> list = new LinkedList<List<Object>>(); 
		// String path = System.getProperty("user.dir") + 
		// System.getProperty("file.separator")+"dd.xlsx"; 
		// System.out.println("路徑:"+path); 
		//構造XSSFWorkbook對象,strPath傳入文件路徑
		XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file)); 
		// 讀取第一章表格內容
		XSSFSheet sheet = xwb.getSheetAt(0); 
		Object value = null; 
		XSSFRow row = null; 
		XSSFCell cell = null; 
		System.out.println("讀取office 2007 excel內容如下:"); 
		for (int i = sheet.getFirstRowNum(); i <= sheet.getPhysicalNumberOfRows(); i++) { 
			row = sheet.getRow(i); 
			if (row == null) { 
				continue; 
			}
			List<Object> linked = new LinkedList<Object>();    
			for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {     
				cell = row.getCell(j);     
				if (cell == null) {      
					continue;     
				}     
				DecimalFormat df = new DecimalFormat("0");// 格式化 number String     
				// 字符     
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串     
				DecimalFormat nf = new DecimalFormat("0.00");// 格式化數字      
				switch (cell.getCellType()) {      
				case XSSFCell.CELL_TYPE_STRING:      
					// System.out.println(i + "行" + j + " 列 is String type");      
					value = cell.getStringCellValue();      
					System.out.print("  " + value + "  ");      
					break;         
					case XSSFCell.CELL_TYPE_NUMERIC:
					// System.out.println(i + "行" + j 
					// + "列is Number type  DateFormt:" 
					// + cell.getCellStyle().getDataFormatString()); 
					if ("@".equals(cell.getCellStyle().getDataFormatString())) { 
						value = df.format(cell.getNumericCellValue()); 
					} else if ("General".equals(cell.getCellStyle().getDataFormatString())) { 
						value = nf.format(cell.getNumericCellValue()); 
					} else { 
						value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())); 
					} 
					System.out.print(" " + value + " "); 
					break; 
				case XSSFCell.CELL_TYPE_BOOLEAN: 
					// System.out.println(i + "行" + j + "列is Boolean type"); 
					value = cell.getBooleanCellValue(); 
					System.out.print(" " + value + " "); 
					break; 
				case XSSFCell.CELL_TYPE_BLANK: 
					// System.out.println(i + "行" + j + "列is Blank type"); 
					value = " ";
					// System.out.println(value); 
					break;
				default: 
					// System.out.println(i + "行" + j + "列is default type"); 
					value = cell.toString(); 
					System.out.print(" " + value + " "); 
				} 
				if (value == null || " ".equals(value)) { 
					continue; 
				} 
				linked.add(value); 
			} 
			System.out.println(" "); 
			list.add(linked); 
		}
		return list;
	}
}

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