POI工具类

package com.ysq.ssm.poi;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFFont;import org.apache.poi.hssf.usermodel.HSSFPalette;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;

import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.lang.reflect.Method;import java.net.URLEncoder;import java.text.DecimalFormat;import java.util.List;

/** * Created by yangshuqi on 17-5-3. */public class PoiExcelExport {    HttpServletResponse response;    // 文件名    private String fileName;    //文件保存路径    private String fileDir;    //sheet名    private String sheetName;    //表头字体    private String titleFontType = "Arial Unicode MS";    //表头背景色    private String titleBackColor = "C1FBEE";    //表头字号    private short titleFontSize = 12;    //添加自动筛选的列 如 A:M    private String address = "";    //正文字体    private String contentFontType = "Arial Unicode MS";    //正文字号    private short contentFontSize = 12;    //Float类型数据小数位    private String floatDecimal = ".00";    //Double类型数据小数位    private String doubleDecimal = ".00";    //设置列的公式    private String colFormula[] = null;

DecimalFormat floatDecimalFormat = new DecimalFormat(floatDecimal);    DecimalFormat doubleDecimalFormat = new DecimalFormat(doubleDecimal);

private HSSFWorkbook workbook = null;

public PoiExcelExport(String fileDir, String sheetName) {        this.fileDir = fileDir;        this.sheetName = sheetName;        workbook = new HSSFWorkbook();    }

public PoiExcelExport(HttpServletResponse response, String fileName, String sheetName) {        this.response = response;        this.sheetName = sheetName;        workbook = new HSSFWorkbook();    }

/**     * 设置表头字体.     *     * @param titleFontType     */    public void setTitleFontType(String titleFontType) {        this.titleFontType = titleFontType;    }

/**     * 设置表头背景色.     *     * @param titleBackColor 十六进制     */    public void setTitleBackColor(String titleBackColor) {        this.titleBackColor = titleBackColor;    }

/**     * 设置表头字体大小.     *     * @param titleFontSize     */    public void setTitleFontSize(short titleFontSize) {        this.titleFontSize = titleFontSize;    }

/**     * 设置表头自动筛选栏位,如A:AC.     *     * @param address     */    public void setAddress(String address) {        this.address = address;    }

/**     * 设置正文字体.     *     * @param contentFontType     */    public void setContentFontType(String contentFontType) {        this.contentFontType = contentFontType;    }

/**     * 设置正文字号.     *     * @param contentFontSize     */    public void setContentFontSize(short contentFontSize) {        this.contentFontSize = contentFontSize;    }

/**     * 设置float类型数据小数位 默认.00     *     * @param doubleDecimal 如 ".00"     */    public void setDoubleDecimal(String doubleDecimal) {        this.doubleDecimal = doubleDecimal;    }

/**     * 设置doubel类型数据小数位 默认.00     *     * @param floatDecimalFormat 如 ".00     */    public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {        this.floatDecimalFormat = floatDecimalFormat;    }

/**     * 设置列的公式     *     * @param colFormula 存储i-1列的公式 涉及到的行号使用@替换 如[email protected][email protected]     */    public void setColFormula(String[] colFormula) {        this.colFormula = colFormula;    }

/**     * 写excel.     *     * @param titleColumn 对应bean的属性名     * @param titleName   excel要导出的表名     * @param dataList    数据     */    public void wirteExcel(String titleColumn[], String titleName[], List<?> dataList) {        //添加Worksheet(不添加sheet时生成的xls文件打开时会报错)        Sheet sheet = workbook.createSheet(this.sheetName);        //新建文件        OutputStream out = null;        try {            if (fileDir != null) {                //有文件路径                out = new FileOutputStream(fileDir);            } else {                //否则,直接写到输出流中                out = response.getOutputStream();                fileName = fileName + ".xls";                response.setContentType("application/x-msdownload");                response.setHeader("Content-Disposition", "attachment; filename="                        + URLEncoder.encode(fileName, "UTF-8"));            }

//写入excel的表头            Row titleNameRow = workbook.getSheet(sheetName).createRow(0);            //设置样式            HSSFCellStyle titleStyle = workbook.createCellStyle();            titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);            titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short) 10);

for (int i = 0; i < titleName.length; i++) {                Cell cell = titleNameRow.createCell(i);                cell.setCellStyle(titleStyle);                cell.setCellValue(titleName[i].toString());            }

//通过反射获取数据并写入到excel中            if (dataList != null && dataList.size() > 0) {                //设置样式                HSSFCellStyle dataStyle = workbook.createCellStyle();                titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize);

if (titleColumn.length > 0) {                    for (int rowIndex = 1; rowIndex <= dataList.size(); rowIndex++) {                        Object obj = dataList.get(rowIndex - 1);     //获得该对象                        Class clsss = obj.getClass();     //获得该对对象的class实例                        Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);                        for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {                            String title = titleColumn[columnIndex].toString().trim();                            if (!"".equals(title)) {  //字段不为空                                //使首字母大写//                                String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;//                                String methodName = "get" + UTitle;                                String getMethodName = "get" + title.substring(0, 1).toUpperCase() + title.substring(1);

// 设置要执行的方法                                Method method = clsss.getDeclaredMethod(getMethodName);

//获取返回类型                                String returnType = method.getReturnType().getName();

String data = method.invoke(obj) == null ? "" : method.invoke(obj).toString();                                Cell cell = dataRow.createCell(columnIndex);                                if (data != null && !"".equals(data)) {                                    if ("int".equals(returnType)) {                                        cell.setCellValue(Integer.parseInt(data));                                    } else if ("long".equals(returnType)) {                                        cell.setCellValue(Long.parseLong(data));                                    } else if ("float".equals(returnType)) {                                        cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));                                    } else if ("double".equals(returnType)) {                                        cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));                                    } else {                                        cell.setCellValue(data);                                    }                                }                            } else {   //字段为空 检查该列是否是公式                                if (colFormula != null) {                                    String sixBuf = colFormula[columnIndex].replace("@", (rowIndex + 1) + "");                                    Cell cell = dataRow.createCell(columnIndex);                                    cell.setCellFormula(sixBuf.toString());                                }                            }                        }                    }

}            }            workbook.write(out);        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                out.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }

/**     * 将16进制的颜色代码写入样式中来设置颜色     *     * @param style 保证style统一     * @param color 颜色:66FFDD     * @param index 索引 8-64 使用时不可重复     * @return     */    public CellStyle setColor(CellStyle style, String color, short index) {        if (color != "" && color != null) {            //转为RGB码            int r = Integer.parseInt((color.substring(0, 2)), 16);   //转为16进制            int g = Integer.parseInt((color.substring(2, 4)), 16);            int b = Integer.parseInt((color.substring(4, 6)), 16);            //自定义cell颜色            HSSFPalette palette = workbook.getCustomPalette();            palette.setColorAtIndex((short) index, (byte) r, (byte) g, (byte) b);

style.setFillPattern(CellStyle.SOLID_FOREGROUND);            style.setFillForegroundColor(index);        }        return style;    }

/**     * 设置字体并加外边框     *     * @param style 样式     * @param style 字体名     * @param style 大小     * @return     */    public CellStyle setFontAndBorder(CellStyle style, String fontName, short size) {        HSSFFont font = workbook.createFont();        font.setFontHeightInPoints(size);        font.setFontName(fontName);        style.setFont(font);        style.setBorderBottom(CellStyle.BORDER_THIN); //下边框        style.setBorderLeft(CellStyle.BORDER_THIN);//左边框        style.setBorderTop(CellStyle.BORDER_THIN);//上边框        style.setBorderRight(CellStyle.BORDER_THIN);//右边框        return style;    }

/**     * 删除文件     *     * @param fileDir     * @return     */    public boolean deleteExcel() {        boolean flag = false;        File file = new File(this.fileDir);        // 判断目录或文件是否存在        if (!file.exists()) {  // 不存在返回 false            return flag;        } else {            // 判断是否为文件            if (file.isFile()) {  // 为文件时调用删除文件方法                file.delete();                flag = true;            }        }        return flag;    }

/**     * 删除文件     *     * @param fileDir     * @return     */    public boolean deleteExcel(String path) {        boolean flag = false;        File file = new File(path);        // 判断目录或文件是否存在        if (!file.exists()) {  // 不存在返回 false            return flag;        } else {            // 判断是否为文件            if (file.isFile()) {  // 为文件时调用删除文件方法                file.delete();                flag = true;            }        }        return flag;    }}
时间: 2024-08-04 15:36:34

POI工具类的相关文章

poi 工具类

<!--POI--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifa

poi操作Excel工具类

在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完成的功能是:读取Excel.写入Excel.合并Excel的功能.

自己封装的poi操作Excel工具类

该工具类主要完成的功能是:读取Excel.汇总Excel的功能.在读取时,可以设定开始和结束读取的位置.设定是否读取多个sheet.设定读取那个或者那些sheet等.在汇总时,如设定是否覆盖目标文件.设定是否比较检查重复内容.设定检查重复的列索引等功能. package com.tgb.ccl.excel.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; impo

一个基于POI的通用excel导入导出工具类的简单实现及使用方法

前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴.经过思考,认为一百个客户在录入excel的时候,就会有一百个格式版本,所以在实现这个功能之前,所以要统一excel的格式.于是提供了一个通用excel模版的下载功能.当所有客户用模版录入好数据再上传到系统,后端对excel进行解析,然后再持久化到数据库. 概述: 此工具类的几大特点 1.基本导入导出

ExeclUtil 工具类(poi + jxl)

jxl 包: poi 包: 使用:List<List<List<String>>> dataList = ExcelUtil.readExcelByPoi(file);//解析文件 结构:sheet—列—行—String List<List<List<String>>> dataList = ExcelUtil.readExcelByPoi(file); import java.io.BufferedInputStream; impo

导入导出封装的工具类 (一) 利用POI封装

对于导入导出各个项目中几乎都会用到,记得在高校平台中封装过导入导出这部分今天看了看是利用JXL封装的而经理说让我用POI写写导出,这两个导入导出框架是目前比较流程和常用的框架,有必要都了解一下. 写了写代码觉得导入导出这一块底层都是一样的,几乎所有的框架和别的牛人也好都是底层利用POI或JXL实现,比的是谁对这部分封装的好而且每个项目中对导入导出具体的细节是不同的,因此,有必要了解了解怎么样操作POI,学学使用它的API做导入导出也许第一步你封装的没有别人那么好,你也会收获很多了解他们封装的思路

POI读取excel工具类 返回实体bean集合

本文举个简单的实例 读取上图的 excel文件到 List<User>集合 首先 导入POi 相关 jar包 在pom.xml 加入 <!-- poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> &l

使用回调方式写POI导入excel工具类

场景是这样的:为了做一个excel导入的功能,为了尽可能的写一个通用的工具类,将与poi有关的东西都封装起来,以便以其他人员只用关心自己的业务,不用和poi打交道. 写到最后,现在还是会有poi的东西暴漏出来一点,暴漏出来的这个应该是必须的. 为了模拟这个场景,先写两个service方法,用于和数据库交互,存入从模板中读取的数据.代码如下: 1.berthservice public class BerthService { public void update(){ System.out.pr

使用Apache POI写的一个生成Excel的工具类

话不多说,直接上代码,就一个类,注释也写得比较清楚了. /** * */ package com.common.office; import java.io.FileOutputStream; import java.lang.reflect.Field; import java.util.Calendar; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apach