在用java 写数据库应用的时候, 通常会生成各种报表,而这些报表可能会被导出为各种格式的文件,比如Excel文档,pdf 文档等等. 今天先做了一个生成Excel 文档的例子,主要解决以下问题:

  1. 生成 Excel 文档.

  2. 保护生成Excel文档,设置密码访问.

  3. 自动对生成的Excel 文档第一行标题栏设置成filter 过滤形式, 方便用户使用.

package com.yihaomen.poi.sample;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
/**
 * Excel util, create excel sheet, cell and style.
 * @param <T> generic class.
 */
public class ExcelUtil<T> {
   
    public HSSFCellStyle getCellStyle(HSSFWorkbook workbook,boolean isHeader){
        HSSFCellStyle style = workbook.createCellStyle();
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setLocked(true);
        if (isHeader) {
            style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            HSSFFont font = workbook.createFont();
            font.setColor(HSSFColor.BLACK.index);
            font.setFontHeightInPoints((short) 12);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            style.setFont(font);
        }        
        return style;
    }
    
   
    public  void generateHeader(HSSFWorkbook workbook,HSSFSheet sheet,String[] headerColumns){
        HSSFCellStyle style = getCellStyle(workbook,true);
        Row row = sheet.createRow(0);
        row.setHeightInPoints(30);
        for(int i=0;i<headerColumns.length;i++){
            Cell cell = row.createCell(i);
            String[] column = headerColumns[i].split("_#_");
            sheet.setColumnWidth(i, Integer.valueOf(column[1]));
            cell.setCellValue(column[0]);
            cell.setCellStyle(style);
        }
    }    
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public  HSSFSheet creatAuditSheet(HSSFWorkbook workbook,String sheetName,List<T> dataset,String[] headerColumns,String[] fieldColumns) 
            throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        
        HSSFSheet sheet = workbook.createSheet(sheetName);
        sheet.protectSheet("");
        
        generateHeader(workbook,sheet,headerColumns); 
        HSSFCellStyle style = getCellStyle(workbook,false);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        int rowNum = 0;
        for(T t:dataset){
            rowNum++ ;
            Row row = sheet.createRow(rowNum); 
            row.setHeightInPoints(25);
            for(int i = 0; i < fieldColumns.length; i++){  
                String fieldName = fieldColumns[i] ; 
               
                String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1); 
                try {                    
                    Class clazz = t.getClass();
                    Method getMethod;
                    getMethod = clazz.getMethod(getMethodName, new Class[]{} );
                    Object value = getMethod.invoke(t, new Object[]{});
                    String cellValue = "";
                    if (value instanceof Date){
                        Date date = (Date)value;
                        cellValue = sd.format(date);
                    }else{ 
                        cellValue = null != value ? value.toString() : "";
                    }  
                    Cell cell = row.createCell(i);
                    cell.setCellStyle(style);
                    cell.setCellValue(cellValue);
                   
                } catch (Exception e) {
                    
                } 
            }  
        }
        return sheet; 
    }
}

这一个公用的类,主要生成Excel的头,正文,以及Excel 文档的样式。看方法名称基本就可以知道这个方法是干什么用的

package com.yihaomen.poi.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.yihaomen.poi.sample.ExcelUtil;
import com.yihaomen.poi.sample.User; public class PoiTest {
    
     /*excel column formate:column_#_width, excel中每一列的名称*/
    public static final String[] USER_RECORES_COLUMNS = new String[]{
            "User Name_#_3000",
            "Address_#_7000"  
     };
     
    /*the column will display on xls files. must the same as the entity fields.对应上面的字段.*/
    public static final String[] USER_RECORES_FIELDS = new String[]{
        "name","address"
    };
    
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
        List<User> users = new ArrayList<User>();
        for(int i=0; i<10;i++){
            User u = new User();
            u.setAddress("address :" + i);
            u.setName("name: "+ i);
            u.setAge(i);
            users.add(u);
        }
        
        //实际项目中,这个list 估计是从数据库中得到的
        
        HSSFWorkbook workbook = new HSSFWorkbook();
        ExcelUtil<User> userSheet = new ExcelUtil<User>();
        userSheet.creatAuditSheet(workbook, "user sheet xls", 
                users, USER_RECORES_COLUMNS, USER_RECORES_FIELDS);
        
        FileOutputStream fileOut = new FileOutputStream("d:/yihaomen_user_test.xls"); 
        workbook.write(fileOut); 
        fileOut.close(); 
    }
}

这里直接保存文件到 D 盘下面,主要是为了自己测试方便. 另外还需要一个测试需要的

package com.yihaomen.poi.sample;

public class User {
    
    private String name;
    private int age;
    private String address;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

生成的文档,你是不能修改的,原因很简单,设置了一个空密码,虽然是空密码,Excel 还是会出现提示,当然你可以直接解保护. 实现的主要代码是在 ExcelUtil 中的 creatAuditSheet 方法中的:

sheet.protectSheet(""); // 设置了一个空的密码

如果要实现第一行标题自动过滤怎么处理呢,可以在上面提到的方法中加入如下代码:

char[] endChar = Character.toChars( 'A' + (headerColumns.length - 1) );
String rangeAddress = "A1:" + String.valueOf(endChar) + "1";
sheet.setAutoFilter(CellRangeAddress.valueOf(rangeAddress));

http://www.ibloger.net/article/3243.html

Java 利用 poi 生成 Excel文件的通用例子的更多相关文章

  1. java利用poi生成excel文件后下载本地

    1.该功能需要poi的jar包,链接: http://pan.baidu.com/s/1migAtNq 密码: 38fx. 2.首先新建一个实体类,用以存放单个数据 public class Test ...

  2. Java利用POI生成Excel强制换行

    前一段时间在做一个学校排课系统时,有一个地方需要利用把课程表生成excel汇出给客户,由于之前用excel都只是简单的应用,在单元格里都是用自动换行,而这次可能需要用到手动强制换行. 于是我在网上找了 ...

  3. Java 利用poi生成excel表格

    所需jar包,如下所示 写一个excel工具类 ExcelUtils .java import java.lang.reflect.Field; import java.util.Iterator; ...

  4. java利用poi解析excel文件

    首先需要引入以下jar包 如果使用maven,需要添加两个依赖 <dependencies> <dependency> <groupId>org.apache.po ...

  5. Java Struts2 POI创建Excel文件并实现文件下载

    Java Struts2 POI创建Excel文件并实现文件下载2013-09-04 18:53 6059人阅读 评论(1) 收藏 举报 分类: Java EE(49) Struts(6) 版权声明: ...

  6. Java利用poi生成word(包含插入图片,动态表格,行合并)

    转(小改): Java利用poi生成word(包含插入图片,动态表格,行合并) 2018年12月20日 09:06:51 wjw_11093010 阅读数:70 Java利用poi生成word(包含插 ...

  7. JAVA使用POI读取EXCEL文件的简单model

    一.JAVA使用POI读取EXCEL文件的简单model 1.所需要的jar commons-codec-1.10.jarcommons-logging-1.2.jarjunit-4.12.jarlo ...

  8. POI生成EXCEL文件

    POI生成EXCEL文件 一.背景 根据指定格式的JSON文件生成对应的excel文件,需求如下 支持多sheet 支持单元格合并 支持插入图片 支持单元格样式可定制 需要 标题(title),表头( ...

  9. java通过poi编写excel文件

    public String writeExcel(List<MedicalWhiteList> MedicalWhiteList) { if(MedicalWhiteList == nul ...

随机推荐

  1. PSQL命令小结

    经常使用psql查询数据,现在总结几个常用的命令参数,供以后参考 -h   数据库地址 -U   数据库用户名 -t   不打印字段等信息 -c   执行的SQL语句 -s   单步执行,就是执行的时 ...

  2. MAC LINUX 安装PYQT(事例)

    MAC安装 1.安装命令:brew install pyqt Warning: Your Xcode () is outdated Please install Xcode 5.0. Warning: ...

  3. [转]java 自动装箱与拆箱

    转自:http://www.cnblogs.com/shenliang123/archive/2012/04/16/2451996.html 这个是jdk1.5以后才引入的新的内容,作为秉承发表是最好 ...

  4. java 反汇编class文件

      Created by Marydon on 1.情景展示 如何使用Java命令将字节码文件(class文件)反汇编? 2.解决方案 反汇编:将java文件编译后的class文件反汇编进而看到jav ...

  5. Number of dynamic partitions exceeded hive.exec.max.dynamic.partitions.pernode

    动态分区数太大的问题:[Fatal Error] Operator FS_2 (id=2): Number of dynamic partitions exceeded hive.exec.max.d ...

  6. django之创建第6个项目-过滤器

    1.views.PY # Create your views here. #coding:utf-8 from django.http import HttpResponse import datet ...

  7. 简单的BSON OID生成实现

    简单的OID生成测试实现,只是简单的用用,切勿用于生产环境. /* 应该使用大端序的,这里没有做转换 * ObjectId是12-byte BSON类型,其结构为: * * 4-byte 值为Unix ...

  8. Fix problems that block programs from being installed or removed

    Follow these steps to automatically repair issues including corrupted registry keys that block you f ...

  9. 在spring boot微服务中使用JWS发布webService

    发布时间:2018-11-22   技术:Java+spring+maven   概述 在springboot微服务中使用JWS发布webService,在服务启动时自动发布webservice接口. ...

  10. [转载]RHEL-6启动时提示:“/usr/libexec/gconf-sanit

    原文地址:RHEL-6启动时提示:"/usr/libexec/gconf-sanity-check-2 exited with status 256"作者:huage 系统环境:R ...