认识POI
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
在开源世界中,有两套比较有影响的API可 供开发者使用,一个是POI,一个是JXL,其中功能相对POI比较弱一点,所以我们日常开发中用到更多的往往是POI,在这里我们也只对POI做一个深入的使用讲解,并给出一个导Excel的工具类,适用任何列表的导出。
POI的jar包下载地址
简易的POI写入数据(认识API)
1:建立新HSSFWorkbook对象
HSSFWorkbook wb = new HSSFWorkbook();
2:建立新的sheet对象
HSSFSheet sheet = wb.createSheet("new sheet");
3:在sheet里创建一行,参数为行号
HSSFRow r ow = sheet.createRow((short)0);
4:在row里新建新cell(单元格)参数为列号
4.1、给第一列设置一个整型值
HSSFCell cell = row.createCell((short)0);
cell.setCellValue(1);
4.2、给第二列设置一个浮点型值
HSSFCell cell= row.createCell((short)1);
cell.setCellValue(1.2);
4.3、给第三列设置一个字符串型值
HSSFCell cell = row.createCell((short)2);
cell.setCellValue(“test”);
4.4、给第四列设置一个布尔型值
HSSFCell cell = row.createCell((short)3);
cell.setCellValue(true);
4.5、给第五列设置一个日期型值
设立新的cell样式 :
HSSFCellStyle cellStyle = wb.createCellStyle();
设置cell样式为定制的日期格式:
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("yyyy年MM月dd日"));
HSSFCell cell = row.createCell((short)4);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
5:往磁盘写入excel文件
FileOutputStream os = new FileOutputStream("d:\\test.xls");
wb.write(os);
os.close();
单元格样式设定
HSSFCellStyle style = workbook.createCellStyle();
单元格的顔色有前景色和背景色。
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillBackgroundColor(HSSFColor.SKY_BLUE.index);
POI提供的颜色类:HSSFColor
设定顔色时,用这些子类的静态常量「index」作为参数。
如果这些顔色还不够你用的话,怎么设定自己想要的顔色呢
填充模式
指定填充模式的话,使用「HSSFCellStyle」类的「setFillPattern」方法。
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
值 | 说明 |
---|---|
NO_FILL | No background |
SOLID_FOREGROUND | Solidly filled |
FINE_DOTS | Small fine dots |
ALT_BARS | Wide dots |
SPARSE_DOTS | Sparse dots |
THICK_HORZ_BANDS | Thick horizontal bands |
THICK_VERT_BANDS | Thick vertical bands |
THICK_BACKWARD_DIAG | Thick backward facing diagonals |
THICK_FORWARD_DIAG | Thick forward facing diagonals |
BIG_SPOTS | Large spots |
BRICKS | Brick-like layout |
THIN_HORZ_BANDS | Thin horizontal bands |
THIN_VERT_BANDS | Thin vertical bands |
THIN_BACKWARD_DIAG | Thin backward diagonal |
THIN_FORWARD_DIAG | Thin forward diagonal |
SQUARES | Squares |
DIAMONDS | Diamonds |
设定边框的样式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
设定单元格内容位置
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
文字样式设定
HSSFFont font = workbook.createFont();
设定文字颜色
font.setColor(HSSFColor.VIOLET.index);
设置字体大小
font.setFontHeightInPoints((short) 12);
设置字体粗细度
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
把字体应用到当前的样式
style.setFont(font);
一个通用的工具类
<pre name="code" class="java"><pre name="code" class="java">public class ExportExcelUtil<T>{
/**
* 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
*
* @param title
*
* 表格标题名
*
* @param headers
*
* 表格属性列名数组
*
* @param dataset
*
* 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
* javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
*
* @param out
*
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
*
* @param pattern
*
* 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
*
*/
@SuppressWarnings("unchecked")
public byte[] exportExcel(String title, String[] headers,Collection<T> dataset, String pattern){
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFFont font3 = workbook.createFont();
// 生成一个表格
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置另一个样式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一个字体
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style2.setFont(font2);
HSSFSheet sheet = null;
HSSFRow row = null;
int index = 0;
int sheetnum = 0;
Iterator<T> it = dataset.iterator();
// 产生表格标题行
sheet = workbook.createSheet(title + sheetnum);
sheet.setDefaultColumnWidth((short) 15);
row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
while (it.hasNext()){
index++;
if (index > 50000){
index = 0;
++sheetnum;
sheet = workbook.createSheet(title + sheetnum);
sheet.setDefaultColumnWidth((short) 15);
row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
}
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
try{
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
if (value instanceof Integer){
int intValue = (Integer) value;
cell.setCellValue(intValue);
}
else if (value instanceof Float){
float fValue = (Float) value;
textValue = new HSSFRichTextString(String.valueOf(fValue)).toString();
cell.setCellValue(textValue);
}
else if (value instanceof Double){
double dValue = (Double) value;
textValue = new HSSFRichTextString(String.valueOf(dValue)).toString();
cell.setCellValue(textValue);
}
else if (value instanceof Long){
long longValue = (Long) value;
cell.setCellValue(longValue);
}
if (value instanceof Boolean){
boolean bValue = (Boolean) value;
textValue = "true";
if (!bValue){
textValue = "false";
}
}
else if (value instanceof Date){
Date date = (Date) value;
if ("".equals(pattern)){
pattern = "yyy-MM-dd";
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
}
else{
if (null == value || "".equals(value)){
value = "";
}
else{
textValue = value.toString();
}
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
if (textValue != null){
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches()){
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
}
else{
HSSFRichTextString richString = new HSSFRichTextString(textValue);
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try{
workbook.write(baos);
baos.flush();
}
catch (IOException e){
e.printStackTrace();
}
return baos.toByteArray();
}
}
导入excel
<pre name="code" class="java">public class ExcelReader {
/**
* 读取“.xls”格式使用 import org.apache.poi.hssf.usermodel.*;包的内容,例如:HSSFWorkbook
* 读取“.xlsx”格式使用 import org.apache.poi.xssf.usermodel.*; 包的内容,例如:XSSFWorkbook
* 读取两种格式使用 import org.apache.poi.ss.usermodel.* 包的内容,例如:Workbook
* @param filePath
* @return
*/
public static List<String[]> readExcel(String filePath){
String fullPath = ExcelReader.class.getClassLoader().getResource(filePath).getPath();
Workbook wb = null;
try {
InputStream in = new BufferedInputStream(new FileInputStream(fullPath));
wb = WorkbookFactory.create(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (InvalidFormatException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
List<String[]> list = new ArrayList<String[]>();
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++){
Sheet st = wb.getSheetAt(sheetIndex);
// 第一行为标题,不取
for (int rowIndex = 0; rowIndex <= st.getPhysicalNumberOfRows(); rowIndex++){
Row row = st.getRow(rowIndex);
if (row == null) {
continue;
}
String[] cells = cellArray(row);
list.add(cells);
}
}
return list;
}
private static String[] cellArray(Row row) {
String[] cellArray = new String[row.getPhysicalNumberOfCells()];
for (int index = 0; index < row.getPhysicalNumberOfCells(); index++) {
String value = "";
Cell cell = row.getCell(index);
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING :
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC :
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd").format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0.00").
format(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_FORMULA :
try{
value = String.valueOf(cell.getNumericCellValue());
} catch(IllegalStateException e){
value = String.valueOf(cell.getRichStringCellValue());
}
break;
case HSSFCell.CELL_TYPE_BLANK :
break;
case HSSFCell.CELL_TYPE_ERROR :
value = "";
break;
case HSSFCell.CELL_TYPE_BOOLEAN :
value = (cell.getBooleanCellValue() == true ? "Y" : "N");
break;
default :
value = "";
}
} else {
value = "";
}
cellArray[index] = value;
}
return cellArray;
}
public static void main(String[] args) {
List<String[]> list = readExcel("excel/20160517.xls");
for(String[] arr:list){
System.out.println(Arrays.toString(arr));
}
}
}