使用apache的poi包导出excel表格

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
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 org.apache.poi.ss.util.CellRangeAddress;

public class ExcelUtil {
    /** * Test * @param args */
    public static void main(String[] args){
        String title = "test title";
        String[] head= {"用户ID", "姓名", "年龄", "性别"};
        String[] keys= {"userID", "name", "age", "sex"};
        List data    = new ArrayList<HashMap>();
        Map user1 = new HashMap();
        user1.put("userID", 10001);
        user1.put("name", "Peter");
        user1.put("age", 10);
        user1.put("sex", "male");
        Map user2 = new HashMap();
        user2.put("userID", 10002);
        user2.put("name", "Lily");
        user2.put("age", 12);
        user2.put("sex", "female");
        data.add(user1);
        data.add(user2);
        try {
            HSSFWorkbook wb = getExcel(title, head, keys, data);
            FileOutputStream out = new FileOutputStream("f:\\user_2.xls");
            wb.write(out);
            out.flush();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /** * 将list数据转为excel表格的形式,并以excel文件的形式返回,出错返回null * @author Administrator * @time 2015年7月13日 下午2:34:23 * @param title 标题,可以为空 * @param headeres 列头 * @param keys 列数据键 * @param datalist 数据 * @return * @throws Exception */
    public static HSSFWorkbook getExcel(String title, String[] headeres, String[] keys, List<Map> datalist) throws Exception{

        if(headeres==null){
            throw new Exception("headeres can't be null");
        }
        if(keys==null){
            throw new Exception("keys can't be null");
        }
        if(datalist==null||datalist.size()==0){
            throw new Exception("datalist can't be null or empty");
        }

        if(headeres.length != keys.length){
            throw new Exception("headeres length is not equal keys length");
        }

        Map item = datalist.get(0);//验证是否有相应的数据
        Set keyset = item.keySet();
        for(int i=0; i<keys.length; i++){
            if(!keyset.contains(keys[i])){
                throw new Exception("datalist don't contains keys value");
            }
        }

        int rows = datalist.size();
        int cols = headeres.length;
        int startr = 0;
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        sheet.setDefaultColumnWidth(20);
        if(StringUtils.isNotEmpty(title)){//设置表的标题
            HSSFCell cell = sheet.createRow(0).createCell(0);
            cell.setCellValue(title);
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short)18);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            font.setColor(HSSFColor.BLUE.index);
            font.setItalic(true);
            font.setUnderline(HSSFFont.U_SINGLE);
            style.setFont(font);
            cell.setCellStyle(style);
            CellRangeAddress range = new CellRangeAddress(0, 0, 0, cols-1);
            sheet.addMergedRegion(range);
            startr = 1;
        }

        HSSFRow head = sheet.createRow(startr++);//设置列头
        for(int i=0; i<cols; i++){
            head.createCell(i).setCellValue(headeres[i]);
        }

        for(int i=0; i<rows; i++){//添加数据到表中去
            Map map = datalist.get(i);
            HSSFRow row = sheet.createRow(startr++);
            for(int j=0; j<cols; j++){//添加一条数据
                HSSFCell cell = row.createCell(j);
                Object val = map.get(keys[j]);
                if(val==null){
                    cell.setCellValue("--");
                }else{
                    cell.setCellValue(val.toString());
                }
            }
        }

        return wb;
    }


    /** * 将list数据转为excel表格的形式,并以excel文件的形式返回,出错返回null * @author jian * @param title 标题,可以为空 * @param headeres 列头 * @param keys 列数据键 * @param rowheight 行高 * @param colswidth 每列宽 * @param datalist 数据 * @return * @throws Exception */
    public static HSSFWorkbook getExcel(String title, String[] headeres, String[] keys, short rowheight, int[] colswidth, List<Map> datalist) throws Exception {
        if (headeres==null) {
            throw new Exception("headeres can't be null");
        }
        if (keys==null) {
            throw new Exception("keys can't be null");
        }
        if (datalist==null||datalist.size()==0) {
            throw new Exception("datalist can't be null or empty");
        }
        if (headeres.length != keys.length || headeres.length != colswidth.length) {
            throw new Exception("headeres length is not equal keys length");
        }
        if (rowheight<=0) {
            throw new Exception("row height can't less than zero");
        }
        Map item = datalist.get(0);//验证是否有相应的数据
        Set keyset = item.keySet();
        for (int i=0; i<keys.length; i++) {
            if (!keyset.contains(keys[i])) {
                throw new Exception("datalist don't contains keys value");
            }
        }
        int rows = datalist.size();
        int cols = headeres.length;
        int startr = 0;
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();

        for (int i=0; i<cols; i++) {
            sheet.setColumnWidth(i, colswidth[i]);
        }

        if (StringUtils.isNotEmpty(title)) {//设置表的标题
            HSSFCell cell = sheet.createRow(0).createCell(0);
            cell.setCellValue(title);
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short)18);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            font.setColor(HSSFColor.BLUE.index);
            font.setItalic(true);
            font.setUnderline(HSSFFont.U_SINGLE);
            style.setFont(font);
            cell.setCellStyle(style);
            CellRangeAddress range = new CellRangeAddress(0, 0, 0, cols-1);
            sheet.addMergedRegion(range);
            startr = 1;
        }
        HSSFRow head = sheet.createRow(startr++);//设置列头
        head.setHeight(rowheight);//设置行高
        for (int i=0; i<cols; i++) {
            head.createCell(i).setCellValue(headeres[i]);
        }
        for (int i=0; i<rows; i++) {//添加数据到表中去
            Map map = datalist.get(i);
            HSSFRow row = sheet.createRow(startr++);
            row.setHeight(rowheight);
            for (int j=0; j<cols; j++) {//添加一条数据
                HSSFCell cell = row.createCell(j);
                Object val = map.get(keys[j]);
                if (val==null) {
                    cell.setCellValue("--");
                } else {
                    cell.setCellValue(val.toString());
                }
            }
        }

        return wb;
    }
}

你可能感兴趣的:(poi,Excel)