POI 入门-----读取 Excel 07以上版本

  1.  用for循环读取Excel
package com.csii.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestReadExcel {
	public static void main(String[] args) throws IOException {
		String filePath = "C:\\Users\\ljj\\Desktop\\workDay\\我的事件流\\公共交易试.xlsx";
		File file = new File(filePath);
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		// 07版本以后的excel 对象
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
		// 获取第一个工作表sheet
		XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
		// 获取非空行
		int rowNum = xssfSheet.getLastRowNum();
		// 用于计数
		int i = 1;
		for (int indexRow = 0; indexRow < rowNum; indexRow++) {// 循环每一行
			XSSFRow xssfRow = xssfSheet.getRow(indexRow);
			int colNum = xssfRow.getLastCellNum();

			// 循环每一列
			for (int colIndex = 0; colIndex < colNum; colIndex++) {// 循环每一列
				// 创建一个 单元格(Cell) 对象
				Cell cell = xssfRow.getCell(colIndex);

				if (cell != null) {// 单元格非 null,才输出
					String value = "";
					switch (cell.getCellType()) { // 单元格的三种类型:字符(STRING)、数值                    
                                                      (NUMERIC)、空白(BLANK)
					case STRING:
						value = cell.getStringCellValue();
						break;
					case NUMERIC:
						// 转换成string类型
						value = String.valueOf(cell.getNumericCellValue());
						break;
					case BLANK:
						break;
					default:
						break;
					}
					System.out.println(i++ + ":" + value);

				} else {// 单元格为null,继续寻找下一列的单元格
					continue;
				}
				
			}
		}

	}

}

测试数据如下: 

 


2. 用 Iterater 来循环,此方法比for循环更方便

public class ExcelRead{
	private static XSSFRow row;

	@SuppressWarnings("unused")
	public static void main(String[] args) throws IOException {
		String fileName = "C:\\Users\\ljj\\Desktop\\testExcel\\wc.xlsx";
		String[] arrExcel = readExcel(fileName);
		
		int i = 0;
		for (String string : arrExcel) {
			System.out.println(i + ":" + string);
		}

	}


	/**
	 * 返回一个字段数组
	 * @param fileName
	 * @return String[]
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	public static String[] readExcel(String fileName) throws IOException {

		File file = new File(fileName);
		if (file == null) {
			System.out.println("读取文件失败!");
		}

		FileInputStream fileInputStream = new FileInputStream(file);
		// 创建excel对象
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
		if (file.exists() && file.isFile()) {
			System.out.println("open file succeed!");
		} else {
			System.out.println("Error to open openworkbook.xlsx file!");
		}
		// 获取excel表对象
		XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
        // 创建行的迭代器对象
		Iterator<Row> rowIterator = xssfSheet.iterator();
		// 字段名
		String strName = "";
		// 级字段数
		int i = 0;
		// 存字段数组
		String[] arr = new String[24];
		while (rowIterator.hasNext()) {
			row = (XSSFRow) rowIterator.next();
			Iterator<Cell> cellIterator = row.cellIterator();
			while (cellIterator.hasNext()) {
                // 创建单元格对象
				Cell cell = cellIterator.next();
				switch (cell.getCellType()) {// 根据单元格类型分别获取获取值
				// string 类型
				case STRING:
                    // 获取单元格值
					strName = cell.getStringCellValue();
					strName = strName.trim();
                    // 存入数组中输出
					arr[i++] = strName;
					break;
				// number类型
				case NUMERIC:
                    // 获取单元格值
					strName = String.valueOf(cell.getNumericCellValue());
					strName = strName.trim();
                    // 存入数组中输出
					arr[i++] = strName;
					break;
				default:
					break;
				}
			}
		}
		return arr;
	}
}

测试的表格: 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
读取 Excel 中的日期,可以使用 POI 的 DataFormatter 类将其转换为字符串。下面是一个示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.DateUtil; 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 ReadExcel { public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("sample.xlsx")); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); // Create a DataFormatter object to format the cell values DataFormatter formatter = new DataFormatter(); // Loop through each row and column for (int i = 0; i <= sheet.getLastRowNum(); i++) { XSSFRow row = sheet.getRow(i); if (row != null) { for (int j = 0; j < row.getLastCellNum(); j++) { XSSFCell cell = row.getCell(j); if (cell != null) { String cellValue = formatter.formatCellValue(cell); if (DateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); cellValue = dateFormat.format(date); } System.out.print(cellValue + "\t"); } else { System.out.print("\t"); } } System.out.println(); } } workbook.close(); file.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们首先读取 Excel 文件并获取第一个工作表。然后,我们使用 DataFormatter 类来格式化单元格的值。如果单元格包含日期值,则我们将其转换为字符串。最后,我们输出每个单元格的值。 注意:上面的示例代码假设日期格式为 "yyyy-MM-dd",您可以根据需要更改日期格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值