Apache POI 操作Excel

来源:互联网 发布:浙江师范行知学院qq群 编辑:程序博客网 时间:2024/05/11 05:11

认识POI

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

结构:
HSSF - 提供读写Microsoft Excel格式档案的功能。
XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。
HWPF - 提供读写Microsoft Word格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读写Microsoft Visio格式档案的功能。

在开源世界中,有两套比较有影响的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_FILLNo backgroundSOLID_FOREGROUNDSolidly filledFINE_DOTSSmall fine dotsALT_BARSWide dotsSPARSE_DOTSSparse dotsTHICK_HORZ_BANDSThick horizontal bandsTHICK_VERT_BANDSThick vertical bandsTHICK_BACKWARD_DIAGThick backward facing diagonalsTHICK_FORWARD_DIAGThick forward facing diagonalsBIG_SPOTSLarge spotsBRICKSBrick-like layoutTHIN_HORZ_BANDSThin horizontal bandsTHIN_VERT_BANDSThin vertical bandsTHIN_BACKWARD_DIAGThin backward diagonalTHIN_FORWARD_DIAGThin forward diagonalSQUARESSquaresDIAMONDSDiamonds

设定边框的样式

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));        }    }}



                                             
0 0
原创粉丝点击