- /**
- * 文件名:ExcelReadTest.java
- * 版本信息:
- * 日期:2013-5-2
- * Copyright 足下 Corporation 2013
- * 版权所有
- *
- */
- package com.august.xgame.server.test;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.text.DecimalFormat;
- import java.text.SimpleDateFormat;
- import java.util.LinkedList;
- import java.util.List;
- import org.apache.poi.hssf.usermodel.HSSFDateUtil;
- 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;
- /**
- * 创建时间:2013-5-2 下午2:09:06
- */
- public class ExcelReadTest
- {
- public static void main(String[] args) throws Exception
- {
- readTest(new File("d:/career.xlsx"));
- }
- // 读取Office 2007excel
- public static List<List<Object>> readTest(File file) throws Exception
- {
- List<List<Object>> list = new LinkedList<List<Object>>();
- // 构造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("读取2007excel内容如下:");
- 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.println(" " + value + " ");
- break;
- case XSSFCell.CELL_TYPE_NUMERIC:
- 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.println(" " + value + " ");
- break;
- case XSSFCell.CELL_TYPE_BOOLEAN:
- value = cell.getBooleanCellValue();
- System.out.println(" " +value + " ");
- break;
- case XSSFCell.CELL_TYPE_BLANK:
- value = "";
- System.out.println(value);
- break;
- default:
- value = cell.toString();
- System.out.println(" " + value + " ");
- break;
- }
- if (value == null || "".equals(value))
- {
- continue;
- }
- linked.add(value);
- }
- System.out.println("");
- list.add(linked);
- }
- return list;
- }
- }
转载于:https://blog.51cto.com/intheway/1191502