first: poi 3.14 要求jdk1.6 或以上
jar包去apache下载就可以了.
另外,要完整运行需要xmlbeans 的jar包, 我下的是 xmlbeans-2.6.0.jar
附件里有 项目所用jar包,测试用的excel,及该项目
项目总共需要3个jar包,除jdk外:
1 poi-3.14-xxxx.jar
2 xmlbeans-2.6.jar
3 poi-ooxml-3.14-xxx.jar
代码如下:
/**
*
*/
package helloWorld.com.cpic;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
/**
* poi读excel文件内容
* @author c_liuhaibin
* @version 2016年6月16日
*/
public class ReadSXLSFile
{
public static void main(String[] x) throws EncryptedDocumentException, InvalidFormatException, IOException
{
String fullFileName ="G:/360data/重要数据/桌面/aaa.xls"; //"G:/360data/重要数据/桌面/aaa.xlsx";
ReadSXLSFile x1 = new ReadSXLSFile();
List<List> list=x1.readFile(fullFileName);
for (List inlist : list)
{
for (Object object : inlist)
{
System.out.println(object.toString());
}
}
}
/**
* read excel file
* @param file Ful Name:include file path
* @return list
* @throws EncryptedDocumentException
* @throws InvalidFormatException
* @throws IOException
*/
public List<List> readFile(String fileName) throws EncryptedDocumentException, InvalidFormatException, IOException
{
//官网说这种方式可以兼容两种格式的excel,03 and 07 的.
List<List> list = new ArrayList<List>();
Workbook workbook = WorkbookFactory.create(new File(fileName));
List<Object> inList = null;
for (Sheet sheet : workbook)
{
System.out.println("sheetName:" + sheet.getSheetName());
for (Row row : sheet)
{
inList = new ArrayList<Object>();
for (Cell cell : row)
{
switch (cell.getCellType())
{
// 字符串
case Cell.CELL_TYPE_STRING:
System.out.print("字符串:"+cell.getRichStringCellValue().getString());
//? or getStringCellValue?
inList.add(cell.getRichStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
// 日期
if (DateUtil.isCellDateFormatted(cell))
{
inList.add(cell.getDateCellValue());
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
System.out.print("日期:"+sdf.format(cell.getDateCellValue()));
}
// 数字
else
{
inList.add(cell.getNumericCellValue());
System.out.print("数字:"+cell.getNumericCellValue());
}
break;
// 布尔
case Cell.CELL_TYPE_BOOLEAN:
inList.add(cell.getBooleanCellValue());
System.out.print("布尔:"+cell.getBooleanCellValue());
break;
// 公式
case Cell.CELL_TYPE_FORMULA:
inList.add(cell.getCellFormula());
System.out.print("公式:"+cell.getCellFormula());
break;
default:
System.out.print("error ");
}
}
System.out.println();
list.add(inList);
}
}
return list;
}
}
只写写helloWorld 当然没问题了,不过还有两个问题,希望高人出来指点一下:
1 cell.getRichStringCellValue() 跟 getStringCellValue 有啥区别?
2 为什么我测试用的excel的日期类型总是以数字格式读出来的?