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格式档案的功能。

项目所需要的jar包可以CSDN下载哦。

在网上看了资料。自己总结了一下。并非本人完全原创代码。

1.Student实体对象。

1package com.pojo; 2 3import java.util.Date; 4/** 5 * 需要的实体对象 6 * @author XX帅 7 * @修改日期 2014-8-19下午2:25:42 8 */ 9public class Student { 10    private int id; 11    private int age; 12    private String name; 13    private Date days; 14     15    public Student() { 16        // TODO Auto-generated constructor stub 17    } 18    public Student(int id, int age, String name, Date days) { 19        super(); 20        this.id = id; 21        this.age = age; 22        this.name = name; 23        this.days = days; 24    } 25    public int getId() { 26        return id; 27    } 28    public void setId(int id) { 29        this.id = id; 30    } 31    public int getAge() { 32        return age; 33    } 34    public void setAge(int age) { 35        this.age = age; 36    } 37    public String getName() { 38        return name; 39    } 40    public void setName(String name) { 41        this.name = name; 42    } 43    public Date getDays() { 44        return days; 45    } 46    public void setDays(Date days) { 47        this.days = days; 48    }  49}

2.具体代码实现

1package com.outdisk; 2 3import java.io.FileOutputStream; 4import java.text.SimpleDateFormat; 5import java.util.ArrayList; 6import java.util.List; 7 8import org.apache.poi.hssf.usermodel.HSSFCell; 9import org.apache.poi.hssf.usermodel.HSSFCellStyle; 10import org.apache.poi.hssf.usermodel.HSSFFont; 11import org.apache.poi.hssf.usermodel.HSSFRow; 12import org.apache.poi.hssf.usermodel.HSSFSheet; 13import org.apache.poi.hssf.usermodel.HSSFWorkbook; 14import org.apache.poi.hssf.util.HSSFColor; 15 16import com.pojo.Student; 17/** 18 * POI-Excel手动输入数据导出 19 * @author XX帅 20 * @修改日期 2014-8-19下午2:20:05 21 */ 22public class CreateSimpleExcelToDisk { 23    /** 24     * 手动创建的数据 25     * @return 26     * @throws Exception 27     */ 28    public static List<Student> getStudents () throws Exception{ 29        List<Student> list = new ArrayList<Student>(); 30        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 31        //Student student = new Student(id, age, name, days); 32        Student student1 = new Student(1, 18, "tom", format.parse("2014-08-19")); 33        Student student2 = new Student(2, 19, "tom", format.parse("2014-08-20")); 34        Student student3 = new Student(3, 20, "tom", format.parse("2014-08-21")); 35        list.add(student1); 36        list.add(student2); 37        list.add(student3); 38        return list; 39    } 40    public static void main(String[] args) throws Exception { 41        // 第一步,创建一个workbook,对应一个Excel文件 42        HSSFWorkbook workbook = new HSSFWorkbook(); 43        // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet 44        HSSFSheet hssfSheet = workbook.createSheet("sheet1"); 45        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short 46        HSSFRow hssfRow = hssfSheet.createRow(0); 47        // 第四步,创建单元格,并设置值表头 设置表头居中 48        HSSFCellStyle hssfCellStyle = workbook.createCellStyle(); 49        //居中样式 50        hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 51        HSSFFont font = workbook.createFont(); 52        font.setColor(HSSFColor.VIOLET.index); 53        font.setFontHeightInPoints((short) 16); 54        hssfCellStyle.setFont(font); 55         56        HSSFCell hssfCell = hssfRow.createCell(0);//列索引从0开始 57        hssfCell.setCellValue("学号");//列名1 58        hssfCell.setCellStyle(hssfCellStyle);//列居中显示 59        hssfCell = hssfRow.createCell(1); 60        hssfCell.setCellValue("年龄");//列名2 61        hssfCell.setCellStyle(hssfCellStyle); 62        hssfCell = hssfRow.createCell(2); 63        hssfCell.setCellValue("姓名");//列名3 64        hssfCell.setCellStyle(hssfCellStyle); 65        hssfCell = hssfRow.createCell(3); 66        hssfCell.setCellValue("生日");//列名4 67        hssfCell.setCellStyle(hssfCellStyle); 68         69        // 第五步,写入实体数据 实际应用中这些数据从数据库得到, 70        List<Student> list = CreateSimpleExcelToDisk.getStudents(); 71        for (int i = 0; i < list.size(); i++) { 72            hssfRow = hssfSheet.createRow(i+1); 73            Student student = list.get(i); 74            // 第六步,创建单元格,并设置值 75            hssfRow.createCell(0).setCellValue(student.getId()); 76            hssfRow.createCell(1).setCellValue(student.getAge()); 77            hssfRow.createCell(2).setCellValue(student.getName()); 78            hssfRow.createCell(3).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(student.getDays())); 79        } 80        // 第七步,将文件存到指定位置 81        try { 82            FileOutputStream fileOutputStream = new FileOutputStream("E:/student.xls");//指定路径与名字和格式 83            workbook.write(fileOutputStream);//讲数据写出去 84            fileOutputStream.close();//关闭输出流 85        } catch (Exception e) { 86            e.printStackTrace(); 87        } 88    } 89}

**1.ExportExcel 工具类代码
**

1package com.xs.demo.service; 2 3import java.io.*; 4import java.lang.reflect.*; 5import java.text.SimpleDateFormat; 6import java.util.*; 7import java.util.regex.*; 8 9import javax.swing.JOptionPane; 10 11import org.apache.poi.hssf.usermodel.*; 12 13import org.apache.poi.hssf.util.HSSFColor; 14import org.apache.poi.ss.formula.functions.T; 15 16import com.xs.demo.entity.Userinfo; 17 18public class ExportExcel<T> { 19        public void exportExcel(Collection<T> dataset, OutputStream out)   20        {   21            exportExcel("测试POI导出EXCEL文档1", null, dataset, out, "yyyy-MM-dd");   22        }   23       24        public void exportExcel(String[] headers, Collection<T> dataset,   25                OutputStream out)   26        {   27            exportExcel("测试POI导出EXCEL文档2", headers, dataset, out, "yyyy-MM-dd");   28        }   29       30        public void exportExcel(String[] headers, Collection<T> dataset,   31                OutputStream out, String pattern)   32        {   33            exportExcel("测试POI导出EXCEL文档3", headers, dataset, out, pattern);   34        }   35       36        /**  37         * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上  38         *   39         * @param title  40         *            表格标题名  41         * @param headers  42         *            表格属性列名数组  43         * @param dataset  44         *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的  45         *            javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)  46         * @param out  47         *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中  48         * @param pattern  49         *            如果有时间数据,设定输出格式。默认为"yyy-MM-dd"  50         */   51        @SuppressWarnings("unchecked")   52        public void exportExcel(String title, String[] headers,   53                Collection<T> dataset, OutputStream out, String pattern)   54        {   55            // 声明一个工作薄   56            HSSFWorkbook workbook = new HSSFWorkbook();   57            // 生成一个表格   58            HSSFSheet sheet = workbook.createSheet(title);   59            // 设置表格默认列宽度为15个字节   60            sheet.setDefaultColumnWidth((short) 15);   61            // 生成一个样式   62            HSSFCellStyle style = workbook.createCellStyle();   63            // 设置这些样式   64            style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);   65            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);   66            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);   67            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);   68            style.setBorderRight(HSSFCellStyle.BORDER_THIN);   69            style.setBorderTop(HSSFCellStyle.BORDER_THIN);   70            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);   71            // 生成一个字体   72            HSSFFont font = workbook.createFont();   73            font.setColor(HSSFColor.VIOLET.index);   74            font.setFontHeightInPoints((short) 12);   75            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);   76            // 把字体应用到当前的样式   77            style.setFont(font);   78            // 生成并设置另一个样式   79            HSSFCellStyle style2 = workbook.createCellStyle();   80            style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);   81            style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);   82            style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);   83            style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);   84            style2.setBorderRight(HSSFCellStyle.BORDER_THIN);   85            style2.setBorderTop(HSSFCellStyle.BORDER_THIN);   86            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);   87            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);   88            // 生成另一个字体   89            HSSFFont font2 = workbook.createFont();   90            font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);   91            // 把字体应用到当前的样式   92            style2.setFont(font2);   93       94            // 声明一个画图的顶级管理器   95            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();   96            // 定义注释的大小和位置,详见文档   97            HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,   98                    0, 0, 0, (short) 4, 2, (short) 6, 5));   99            // 设置注释内容   100            comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));   101            // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.   102            comment.setAuthor("leno");   103       104            // 产生表格标题行   105            HSSFRow row = sheet.createRow(0);   106            for (short i = 0; i < headers.length; i++)   107            {   108                HSSFCell cell = row.createCell(i);   109                cell.setCellStyle(style);   110                HSSFRichTextString text = new HSSFRichTextString(headers[i]);   111                cell.setCellValue(text);   112            }   113       114            // 遍历集合数据,产生数据行   115            Iterator<T> it = dataset.iterator();   116            int index = 0;   117            while (it.hasNext())   118            {   119                index++;   120                row = sheet.createRow(index);   121                T t = (T) it.next();   122                // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值   123                Field[] fields = t.getClass().getDeclaredFields();   124                for (short i = 0; i < fields.length; i++)   125                {   126                    HSSFCell cell = row.createCell(i);   127                    cell.setCellStyle(style2);   128                    Field field = fields[i];   129                    String fieldName = field.getName();   130                    String getMethodName = "get"   131                            + fieldName.substring(0, 1).toUpperCase()   132                            + fieldName.substring(1);   133                    try   134                    {   135                        Class tCls = t.getClass();   136                        Method getMethod = tCls.getMethod(getMethodName,   137                                new Class[]   138                                {});   139                        Object value = getMethod.invoke(t, new Object[]   140                        {});   141                        // 判断值的类型后进行强制类型转换   142                        String textValue = null;   143                        if (value instanceof Boolean)   144                        {   145                            boolean bValue = (Boolean) value;   146                            textValue = "男";   147                            if (!bValue)   148                            {   149                                textValue = "女";   150                            }   151                        }   152                        else if (value instanceof Date)   153                        {   154                            Date date = (Date) value;   155                            SimpleDateFormat sdf = new SimpleDateFormat(pattern);   156                            textValue = sdf.format(date);   157                        }   158                        else if (value instanceof byte[])   159                        {   160                            // 有图片时,设置行高为60px;   161                            row.setHeightInPoints(60);   162                            // 设置图片所在列宽度为80px,注意这里单位的一个换算   163                            sheet.setColumnWidth(i, (short) (35.7 * 80));   164                            // sheet.autoSizeColumn(i);   165                            byte[] bsValue = (byte[]) value;   166                            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,   167                                    1023, 255, (short) 6, index, (short) 6, index);   168                            anchor.setAnchorType(2);   169                            patriarch.createPicture(anchor, workbook.addPicture(   170                                    bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));   171                        }   172                        else   173                        {   174                            // 其它数据类型都当作字符串简单处理   175                            textValue = value.toString();   176                        }   177                        // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成   178                        if (textValue != null)   179                        {   180                            Pattern p = Pattern.compile("^//d+(//.//d+)?$");   181                            Matcher matcher = p.matcher(textValue);   182                            if (matcher.matches())   183                            {   184                                // 是数字当作double处理   185                                cell.setCellValue(Double.parseDouble(textValue));   186                            }   187                            else   188                            {   189                                HSSFRichTextString richString = new HSSFRichTextString(   190                                        textValue);   191                                HSSFFont font3 = workbook.createFont();   192                                font3.setColor(HSSFColor.BLUE.index);   193                                richString.applyFont(font3);   194                                cell.setCellValue(richString);   195                            }   196                        }   197                    }   198                    catch (SecurityException e)   199                    {   200                        e.printStackTrace();   201                    }   202                    catch (NoSuchMethodException e)   203                    {   204                        e.printStackTrace();   205                    }   206                    catch (IllegalArgumentException e)   207                    {   208                        e.printStackTrace();   209                    }   210                    catch (IllegalAccessException e)   211                    {   212                        e.printStackTrace();   213                    }   214                    catch (InvocationTargetException e)   215                    {   216                        e.printStackTrace();   217                    }   218                    finally   219                    {   220                        // 清理资源   221                    }   222                }   223            }   224            try   225            {   226                workbook.write(out);   227            }   228            catch (IOException e)   229            {   230                e.printStackTrace();   231            }   232        }  233        public static void main(String[] args) { 234            // 测试学生   235            ExportExcel<Userinfo> ex = new ExportExcel<Userinfo>();   236            String[] headers =   237            { "学号", "姓名", "年龄", "性别", "出生日期" };   238            List<Userinfo> dataset = new ArrayList<Userinfo>();   239            dataset.add(new Userinfo(101, "11", 15, new Date(), "888888", "Asia")); 240            dataset.add(new Userinfo(102, "11", 15, new Date(), "888888", "Asia")); 241            dataset.add(new Userinfo(103, "11", 15, new Date(), "888888", "Asia")); 242            dataset.add(new Userinfo(104, "11", 15, new Date(), "888888", "Asia")); 243            dataset.add(new Userinfo(105, "11", 15, new Date(), "888888", "Asia")); 244            // 测试图书   245            try   246            {   247                OutputStream out = new FileOutputStream("E://a.xls");   248                ex.exportExcel(headers, dataset, out);   249                out.close();   250                JOptionPane.showMessageDialog(null, "导出成功!");   251                System.out.println("excel导出成功!");   252            }   253            catch (FileNotFoundException e)   254            {   255                e.printStackTrace();   256            }   257            catch (IOException e)   258            {   259                e.printStackTrace();   260            }   261            }   262         263        }

个人微博 http://weibo.com/u/2205636212

个人博客 http://my.oschina.net/xshuai/blog

公开QQ  783021975

个人联盟 http://www.bengbeng.com/?sid=687095

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

15道非常经典的Java面试题

试题如下:!(http://static.oschina.net/uploads/space/2016/0729/022902_IBMr_121944.jpg)!(http://static.oschina.net/uploads/space/2016/0729/022923_Exeo_121944.jpg)!(http://static.o

AngularJS 学习笔记 (六) 基本概念和用法 之 Service与Provider

1、使用$http服务!(http://static.oschina.net/uploads/space/2016/0623/092916_7mPM_199513.gif)HTML代码:!(http://static.oschina.net/uploads/space/2016/0623/093044_Y

Android蓝牙连接汽车OBD设备

//设备连接public class BluetoothConnect implements Runnable {    private static final UUID CONNECT_UUID  UUID.fromString("0000110100001000800000805F9B34FB");