Java操作excel

来源:互联网 发布:阿黛尔网络暴力 编辑:程序博客网 时间:2024/06/10 12:09

前情提要:某个项目中需要导出数据到excel,计划使用POI进行操作,如后面还有新的操作excel的方式,也补充到这里。

一、POI的demo

附加操作:

1、导入包:poi-3.9.jar ;

新建文件夹lib,然后将jar包复制到lib里,

Properties->Java Build Path->Libraries->Add JARs->选择POI项目的lib下的jar包即可;

2、建一个 Person 的类,属性 name 和 age;

代码如下所示:

package com.demo.excel;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletResponse;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFFont;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.HSSFColor;import com.demo.bean.Person;/*总结 poi 操作 excel  * 1、获得一个WorkBook(HSSFWorkBook) * 2、获得要读写的Sheet对象 * 3、获得要操作的Row对象 * 4、获得Cell对象--最小的对象 * 5、开始读取、写入 * */public class demoExcel{        public void exportAction()    {        List<Person> personList = new ArrayList<Person>();        Person p1 = new Person();        p1.setAge(18);        p1.setName("susan");        Person p2 = new Person();        p2.setAge(19);        p2.setName("posei");        personList.add(p1);        personList.add(p2);        this.exportExcel2Local(personList);    }    public void exportExcel2Local(List<Person> personList)    {        HSSFWorkbook wb = this.excelList(personList);        FileOutputStream writeFile = null;        try        {            // 创建一个文件输出流,指定到D盘根目录下            // xls是Excel97-2003的标准扩展名,2007是xlsx,目前的POI能直接生产的还是xls格式            // 如果此处把扩展名改成xlsx,在用Excel2007打开此文件时会报错            writeFile = new FileOutputStream("d:/helloworld.xls");            // 把WorkBook写到流里            wb.write(writeFile);            // 记得手动关闭流,官方文档已经做了特别说明,说POI不负责关闭用户打开的流            writeFile.close();        }        catch (Exception e)        {                        e.printStackTrace();        }        finally        {            if (writeFile != null)            {                try                {                    writeFile.close();                }                catch (IOException e)                {                                        e.printStackTrace();                }            }        }            }    public void exportExcel2Jsp(List<Person> personList,HttpServletResponse response)    {        HSSFWorkbook wb = this.excelList(personList);        OutputStream ouputStream = null;        try        {            // 返回给接口            response.setContentType("application/vnd.ms-excel");            response.setHeader(                    "Content-disposition",                    "attachment;filename=" + new String("表格人员".getBytes("gbk"),"iso-8859-1")                            + ".xls");            ouputStream = response.getOutputStream();            wb.write(ouputStream);            ouputStream.flush();            ouputStream.close();        }        catch (Exception e)        {            e.printStackTrace();        }        finally        {            if (ouputStream != null)            {                try                {                    ouputStream.close();                }                catch (IOException e)                {                    e.printStackTrace();                }            }        }    }    public HSSFWorkbook excelList(List<Person> personList)    {                String[] excelHeader = {"姓名","年龄"};        // 创建一个空白的WorkBook              HSSFWorkbook wb = new HSSFWorkbook();        // 基于上面的WorkBook创建属于此WorkBook的Sheet        HSSFSheet sheet = wb.createSheet("表单1人员");        // 创建属于上面Sheet的Row,参数0可以是0~65535之间的任何一个;Excel最多支持65536行        HSSFRow row = sheet.createRow((int) 0);        // 创建一种样式,这里创建的是对齐方式,还有其他方式可以参考手册        // 单元格的边框、字体以及颜色的设置方式,在POI中,这一切都是通过实例化HSSFCellStyle对象来实现的;        // 类似于工厂模式,批量生产一个style然后到处设置        HSSFCellStyle style = wb.createCellStyle();        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);        // 设置单元格的文本方式为可多行编写方式        style.setWrapText(true);        // 还可以创建字体对象        HSSFFont font = wb.createFont();        font.setFontName("宋体");        font.setColor(HSSFColor.BLUE.index);        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);        // 当然,字体也是属于样式,最后要赋给样式对象        style.setFont(font);        // 循环创建列头        for(int i=0;i<excelHeader.length;i++)        {            // 创建属于上面Row的Cell,参数0可以是0~255之间的任何一个;Excel最大支持的列数为256列            HSSFCell cell = row.createCell(i);            // 设置内容            cell.setCellValue(excelHeader[i]);            // 设置格式            cell.setCellStyle(style);            sheet.setDefaultColumnWidth(20);            row.setHeightInPoints(15);//          sheet.setDefaultRowHeightInPoints(20);        }        // 循环填入表单内容        for(int i=0;i<personList.size();i++)        {            row = sheet.createRow(i + 1);            Person p = personList.get(i);            row.createCell(0).setCellValue(p.getName());            row.createCell(1).setCellValue(p.getAge());        }        return wb;    }        public void readExcel()    {        FileInputStream readFile = null;        try        {            // 指定要读取的文件,本例使用上面生成的helloworld.xls            readFile = new FileInputStream("d:/helloworld.xls");            // 创建一个WorkBook,从指定的文件流中创建,即上面指定了的文件流            HSSFWorkbook wb = new HSSFWorkbook(readFile);            // 获取名称为“表单1人员”的sheet;如果不能确定具体的名称,可以用getSheetAt(int)方法取得Sheet            HSSFSheet st = wb.getSheet("表单1人员");            // 获得第一行,同上,如果此行没有被创建过则抛出异常            HSSFRow row = st.getRow(0);            // 获取第一个单元格            HSSFCell cell = row.getCell(0);            // 把cell中的内容按字符串方式读取出来,并显示在控制台上            System.out.println(cell.getRichStringCellValue());            // 记得关闭流            readFile.close();        }        catch (Exception e)        {                        e.printStackTrace();        }        finally        {            if (readFile != null)            {                try                {                    readFile.close();                }                catch (IOException e)                {                                        e.printStackTrace();                }            }        }    }        }



0 0
原创粉丝点击