java导出excel 踏坑

刚开始接触excel的导出,用的是别人的写好的组件,很方便,写一个bean类,把自己的数据加上就行了。不多说,直接上工具类。
public class ExcelHeader implements Comparable<ExcelHeader>{
    /**
     * excel的标题名称
     */
    private String title;
    /**
     * 每一个标题的顺序
     */
    private int order;
    /**
     * 说对应方法名称
     */
    private String methodName;


    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public int getOrder() {
        return order;
    }
    public void setOrder(int order) {
        this.order = order;
    }
    public String getMethodName() {
        return methodName;
    }
    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public int compareTo(ExcelHeader o) {
        return order>o.order?1:(order<o.order?-1:0);
    }
    public ExcelHeader(String title, int order, String methodName) {
        super();
        this.title = title;
        this.order = order;
        this.methodName = methodName;
    }
}

@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelResources {
    /**
     * 属性的标题名称
     * @return
     */
    String title();
    /**
     * 在excel的顺序
     * @return
     */
    int order() default 9999;
}

/**
 * 该类实现了基于模板的导出
 * 如果要导出序号,需要在excel中定义一个标识为sernums
 * 如果要替换信息,需要传入一个Map,这个map中存储着要替换信息的值,在excel中通过#来开头
 * 要从哪一行那一列开始替换需要定义一个标识为datas
 * 如果要设定相应的样式,可以在该行使用styles完成设定,此时所有此行都使用该样式
 * 如果使用defaultStyls作为表示,表示默认样式,如果没有defaultStyles使用datas行作为默认样式
 * Created by 钟述林 393156105@qq.com on 2016/10/28 23:38.
 */
public class ExcelTemplate {

    /**
     * 数据行标识
     */
    public final static String DATA_LINE = "datas";
    /**
     * 默认样式标识
     */
    public final static String DEFAULT_STYLE = "defaultStyles";
    /**
     * 行样式标识
     */
    public final static String STYLE = "styles";
    /**
     * 插入序号样式标识
     */
    public final static String SER_NUM = "sernums";
    private static ExcelTemplate et = new ExcelTemplate();
    private Workbook wb;
    private Sheet sheet;
    /**
     * 数据的初始化列数
     */
    private int initColIndex;
    /**
     * 数据的初始化行数
     */
    private int initRowIndex;
    /**
     * 当前列数
     */
    private int curColIndex;
    /**
     * 当前行数
     */
    private int curRowIndex;
    /**
     * 当前行对象
     */
    private Row curRow;
    /**
     * 最后一行的数据
     */
    private int lastRowIndex;
    /**
     * 默认样式
     */
    private CellStyle defaultStyle;
    /**
     * 默认行高
     */
    private float rowHeight;
    /**
     * 存储某一方所对于的样式
     */
    private Map<Integer,CellStyle> styles;
    /**
     * 序号的列
     */
    private int serColIndex;
    private ExcelTemplate(){

    }
    public static ExcelTemplate getInstance() {
        return et;
    }

    /**
     * 从classpath路径下读取相应的模板文件
     * @param path
     * @return
     */
    public ExcelTemplate readTemplateByClasspath(String path) {
        try {
            wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
            initTemplate();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("读取模板不存在!请检查");
        }
        return this;
    }
    /**
     * 将文件写到相应的路径下
     * @param filepath
     */
    public void writeToFile(String filepath) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filepath);
            wb.write(fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("写入的文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("写入数据失败:"+e.getMessage());
        } finally {
            try {
                if(fos!=null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 将文件写到某个输出流中
     * @param os
     */
    public void wirteToStream(OutputStream os) {
        try {
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("写入流失败:"+e.getMessage());
        }
    }
    /**
     * 从某个路径来读取模板
     * @param path
     * @return
     */
    public ExcelTemplate readTemplateByPath(String path) {
        try {
            wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
            initTemplate();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("读取模板不存在!请检查");
        }
        return this;
    }

    /**
     * 创建相应的元素,基于String类型
     * @param value
     */
    public void createCell(String value) {
        Cell c = curRow.createCell(curColIndex);
        setCellStyle(c);
        c.setCellValue(value);
        curColIndex++;
    }
    public void createCell(int value) {
        Cell c = curRow.createCell(curColIndex);
        setCellStyle(c);
        c.setCellValue((int)value);
        curColIndex++;
    }
    public void createCell(Date value) {
        Cell c = curRow.createCell(curColIndex);
        setCellStyle(c);
        c.setCellValue(value);
        curColIndex++;
    }
    public void createCell(double value) {
        Cell c = curRow.createCell(curColIndex);
        setCellStyle(c);
        c.setCellValue(value);
        curColIndex++;
    }
    public void createCell(boolean value) {
        Cell c = curRow.createCell(curColIndex);
        setCellStyle(c);
        c.setCellValue(value);
        curColIndex++;
    }

    public void createCell(Calendar value) {
        Cell c = curRow.createCell(curColIndex);
        setCellStyle(c);
        c.setCellValue(value);
        curColIndex++;
    }
    public void createCell(BigInteger value) {
        Cell c = curRow.createCell(curColIndex);
        setCellStyle(c);
        c.setCellValue(value==null?0:value.intValue());
        curColIndex++;
    }
    /**
     * 设置某个元素的样式
     * @param c
     */
    private void setCellStyle(Cell c) {
        if(styles.containsKey(curColIndex)) {
            c.setCellStyle(styles.get(curColIndex));
        } else {
            c.setCellStyle(defaultStyle);
        }
    }
    /**
     * 创建新行,在使用时只要添加完一行,需要调用该方法创建
     */
    public void createNewRow() {
        if(lastRowIndex>curRowIndex&&curRowIndex!=initRowIndex) {
            sheet.shiftRows(curRowIndex, lastRowIndex, 1,true,true);
            lastRowIndex++;
        }
        curRow = sheet.createRow(curRowIndex);
        curRow.setHeightInPoints(rowHeight);
        curRowIndex++;
        curColIndex = initColIndex;
    }

    /**
     * 插入序号,会自动找相应的序号标示的位置完成插入
     */
    public void insertSer() {
        int index = 1;
        Row row = null;
        Cell c = null;
        for(int i=initRowIndex;i<curRowIndex;i++) {
            row = sheet.getRow(i);
            c = row.createCell(serColIndex);
            setCellStyle(c);
            c.setCellValue(index++);
        }
    }
    /**
     * 根据map替换相应的常量,通过Map中的值来替换#开头的值
     * @param datas
     */
    public void replaceFinalData(Map<String,String> datas) {
        if(datas==null) return;
        for(Row row:sheet) {
            for(Cell c:row) {
//                if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
                String str = c.getStringCellValue().trim();
                if(str.startsWith("#")) {
                    if(datas.containsKey(str.substring(1))) {
                        c.setCellValue(datas.get(str.substring(1)));
                    }
                }
            }
        }
    }
    /**
     * 基于Properties的替换,依然也是替换#开始的
     * @param prop
     */
    public void replaceFinalData(Properties prop) {
        if(prop==null) return;
        for(Row row:sheet) {
            for(Cell c:row) {
//                if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
                String str = c.getStringCellValue().trim();
                if(str.startsWith("#")) {
                    if(prop.containsKey(str.substring(1))) {
                        c.setCellValue(prop.getProperty(str.substring(1)));
                    }
                }
            }
        }
    }

    private void initTemplate() {
        sheet = wb.getSheetAt(0);
        initConfigData();
        lastRowIndex = sheet.getLastRowNum();
        curRow = sheet.createRow(curRowIndex);
    }
    /**
     * 初始化数据信息
     */
    private void initConfigData() {
        boolean findData = false;
        boolean findSer = false;
        for(Row row:sheet) {
            if(findData) break;
            for(Cell c:row) {
//                if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
                String str = c.getStringCellValue().trim();
                if(str.equals(SER_NUM)) {
                    serColIndex = c.getColumnIndex();
                    findSer = true;
                }
                if(str.equals(DATA_LINE)) {
                    initColIndex = c.getColumnIndex();
                    initRowIndex = row.getRowNum();
                    curColIndex = initColIndex;
                    curRowIndex = initRowIndex;
                    findData = true;
                    defaultStyle = c.getCellStyle();
                    rowHeight = row.getHeightInPoints();
                    initStyles();
                    break;
                }
            }
        }
        if(!findSer) {
            initSer();
        }
    }
    /**
     * 初始化序号位置
     */
    private void initSer() {
        for(Row row:sheet) {
            for(Cell c:row) {
//                if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
                String str = c.getStringCellValue().trim();
                if(str.equals(SER_NUM)) {
                    serColIndex = c.getColumnIndex();
                }
            }
        }
    }
    /**
     * 初始化样式信息
     */
    private void initStyles() {
        styles = new HashMap<Integer, CellStyle>();
        for(Row row:sheet) {
            for(Cell c:row) {
//                if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
                String str = c.getStringCellValue().trim();
                if(str.equals(DEFAULT_STYLE)) {
                    defaultStyle = c.getCellStyle();
                }
                if(str.equals(STYLE)) {
                    styles.put(c.getColumnIndex(), c.getCellStyle());
                }
            }
        }
    }
}

public class ExcelUtil {
    private static ExcelUtil eu = new ExcelUtil();
    private ExcelUtil(){}

    public static ExcelUtil getInstance() {
        return eu;
    }
    /**
     * 处理对象转换为Excel
     * @param template
     * @param objs
     * @param clz
     * @param isClasspath
     * @return
     */
    private ExcelTemplate handlerObj2Excel (String template, List objs, Class clz, boolean isClasspath)  {
        ExcelTemplate et = ExcelTemplate.getInstance();
        try {
            if(isClasspath) {
                et.readTemplateByClasspath(template);
            } else {
                et.readTemplateByPath(template);
            }
            List<ExcelHeader> headers = getHeaderList(clz);
            Collections.sort(headers);
            //输出标题
            et.createNewRow();
            for(ExcelHeader eh:headers) {
                et.createCell(eh.getTitle());
            }
            //输出值
            for(Object obj:objs) {
                et.createNewRow();
                for(ExcelHeader eh:headers) {
                    //              Method m = clz.getDeclaredMethod(mn);
                    //              Object rel = m.invoke(obj);
                    et.createCell(BeanUtils.getProperty(obj,getMethodName(eh)));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return et;
    }
    /**
     * 根据标题获取相应的方法名称
     * @param eh
     * @return
     */
    private String getMethodName(ExcelHeader eh) {
        String mn = eh.getMethodName().substring(3);
        mn = mn.substring(0,1).toLowerCase()+mn.substring(1);
        return mn;
    }
    /**
     * 将对象转换为Excel并且导出,该方法是基于模板的导出,导出到流
     * @param datas 模板中的替换的常量数据
     * @param template 模板路径
     * @param os 输出流
     * @param objs 对象列表
     * @param clz 对象的类型
     * @param isClasspath 模板是否在classPath路径下
     */
    public void exportObj2ExcelByTemplate(Map<String,String> datas, String template, OutputStream os, List objs, Class clz, boolean isClasspath) {
        try {
            ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
            et.replaceFinalData(datas);
            et.wirteToStream(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 将对象转换为Excel并且导出,该方法是基于模板的导出,导出到一个具体的路径中
     * @param datas 模板中的替换的常量数据
     * @param template 模板路径
     * @param outPath 输出路径
     * @param objs 对象列表
     * @param clz 对象的类型
     * @param isClasspath 模板是否在classPath路径下
     */
    public void exportObj2ExcelByTemplate(Map<String,String> datas,String template,String outPath,List objs,Class clz,boolean isClasspath) {
        ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
        et.replaceFinalData(datas);
        et.writeToFile(outPath);
    }

    /**
     * 将对象转换为Excel并且导出,该方法是基于模板的导出,导出到流,基于Properties作为常量数据
     * @param prop 基于Properties的常量数据模型
     * @param template 模板路径
     * @param os 输出流
     * @param objs 对象列表
     * @param clz 对象的类型
     * @param isClasspath 模板是否在classPath路径下
     */
    public void exportObj2ExcelByTemplate(Properties prop, String template, OutputStream os, List objs, Class clz, boolean isClasspath) {
        ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
        et.replaceFinalData(prop);
        et.wirteToStream(os);
    }
    /**
     * 将对象转换为Excel并且导出,该方法是基于模板的导出,导出到一个具体的路径中,基于Properties作为常量数据
     * @param prop 基于Properties的常量数据模型
     * @param template 模板路径
     * @param outPath 输出路径
     * @param objs 对象列表
     * @param clz 对象的类型
     * @param isClasspath 模板是否在classPath路径下
     */
    public void exportObj2ExcelByTemplate(Properties prop,String template,String outPath,List objs,Class clz,boolean isClasspath) {
        ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
        et.replaceFinalData(prop);
        et.writeToFile(outPath);
    }

    private Workbook handleObj2Excel(List objs, Class clz) {
        Workbook wb = new HSSFWorkbook();
        try {
            Sheet sheet = wb.createSheet();
            Row r = sheet.createRow(0);
            List<ExcelHeader> headers = getHeaderList(clz);
            Collections.sort(headers);
            //写标题
            for(int i=0;i<headers.size();i++) {
                r.createCell(i).setCellValue(headers.get(i).getTitle());
            }
            //写数据
            Object obj = null;
            for(int i=0;i<objs.size();i++) {
                r = sheet.createRow(i+1);
                obj = objs.get(i);
                for(int j=0;j<headers.size();j++) {
                    r.createCell(j).setCellValue(BeanUtils.getProperty(obj, getMethodName(headers.get(j))));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return wb;
    }
    /**
     * 导出对象到Excel,不是基于模板的,直接新建一个Excel完成导出,基于路径的导出
     * @param outPath 导出路径
     * @param objs 对象列表
     * @param clz 对象类型
     */
    public void exportObj2Excel(String outPath,List objs,Class clz) {
        Workbook wb = handleObj2Excel(objs, clz);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outPath);
            wb.write(fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fos!=null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 导出对象到Excel,不是基于模板的,直接新建一个Excel完成导出,基于流
     * @param os 输出流
     * @param objs 对象列表
     * @param clz 对象类型
     */
    public void exportObj2Excel(OutputStream os,List objs,Class clz) {
        try {
            Workbook wb = handleObj2Excel(objs, clz);
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 从类路径读取相应的Excel文件到对象列表
     * @param path 类路径下的path
     * @param clz 对象类型
     * @param readLine 开始行,注意是标题所在行
     * @param tailLine 底部有多少行,在读入对象时,会减去这些行
     * @return
     */
    public List<Object> readExcel2ObjsByClasspath(String path,Class clz,int readLine,int tailLine) {
        Workbook wb = null;
        try {
            wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
            return handlerExcel2Objs(wb, clz, readLine,tailLine);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 从文件路径读取相应的Excel文件到对象列表
     * @param path 文件路径下的path
     * @param clz 对象类型
     * @param readLine 开始行,注意是标题所在行
     * @param tailLine 底部有多少行,在读入对象时,会减去这些行
     * @return
     */
    public List<Object> readExcel2ObjsByPath(String path,Class clz,int readLine,int tailLine) {
        Workbook wb = null;
        try {
            wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
            return handlerExcel2Objs(wb, clz, readLine,tailLine);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 从类路径读取相应的Excel文件到对象列表,标题行为0,没有尾行
     * @param path 路径
     * @param clz 类型
     * @return 对象列表
     */
    public List<Object> readExcel2ObjsByClasspath(String path,Class clz) {
        return this.readExcel2ObjsByClasspath(path, clz, 0,0);
    }
    /**
     * 从文件路径读取相应的Excel文件到对象列表,标题行为0,没有尾行
     * @param path 路径
     * @param clz 类型
     * @return 对象列表
     */
    public List<Object> readExcel2ObjsByPath(String path,Class clz) {
        return this.readExcel2ObjsByPath(path, clz,0,0);
    }

    private String getCellValue(Cell c) {
        String o = null;
        switch (c.getCellType()) {
            case Cell.CELL_TYPE_BLANK:
                o = ""; break;
            case Cell.CELL_TYPE_BOOLEAN:
                o = String.valueOf(c.getBooleanCellValue()); break;
            case Cell.CELL_TYPE_FORMULA:
                o = String.valueOf(c.getCellFormula()); break;
            case Cell.CELL_TYPE_NUMERIC:
                o = String.valueOf(c.getNumericCellValue()); break;
            case Cell.CELL_TYPE_STRING:
                o = c.getStringCellValue(); break;
            default:
                o = null;
                break;
        }
        return o;
    }

    private List<Object> handlerExcel2Objs(Workbook wb, Class clz, int readLine, int tailLine) {
        Sheet sheet = wb.getSheetAt(0);
        List<Object> objs = null;
        try {
            Row row = sheet.getRow(readLine);
            objs = new ArrayList<Object>();
            Map<Integer,String> maps = getHeaderMap(row, clz);
            if(maps==null||maps.size()<=0) throw new RuntimeException("要读取的Excel的格式不正确,检查是否设定了合适的行");
            for(int i=readLine+1;i<=sheet.getLastRowNum()-tailLine;i++) {
                row = sheet.getRow(i);
                Object obj = clz.newInstance();
                for(Cell c:row) {
                    int ci = c.getColumnIndex();
                    String mn = maps.get(ci).substring(3);
                    mn = mn.substring(0,1).toLowerCase()+mn.substring(1);
                    BeanUtils.copyProperty(obj,mn, this.getCellValue(c));
                }
                objs.add(obj);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return objs;
    }

    private List<ExcelHeader> getHeaderList(Class clz) {
        List<ExcelHeader> headers = new ArrayList<ExcelHeader>();
        Method[] ms = clz.getDeclaredMethods();
        for(Method m:ms) {
            String mn = m.getName();
            if(mn.startsWith("get")) {
                if(m.isAnnotationPresent(ExcelResources.class)) {
                    ExcelResources er = m.getAnnotation(ExcelResources.class);
                    headers.add(new ExcelHeader(er.title(),er.order(),mn));
                }
            }
        }
        return headers;
    }

    private Map<Integer,String> getHeaderMap(Row titleRow, Class clz) {
        List<ExcelHeader> headers = getHeaderList(clz);
        Map<Integer,String> maps = new HashMap<Integer, String>();
        for(Cell c:titleRow) {
            String title = c.getStringCellValue();
            for(ExcelHeader eh:headers) {
                if(eh.getTitle().equals(title.trim())) {
                    maps.put(c.getColumnIndex(), eh.getMethodName().replace("get","set"));
                    break;
                }
            }
        }
        return maps;
    }
}

public class TemplateFileUtil {

    public static FileInputStream getTemplates(String tempName) throws FileNotFoundException {
        return new FileInputStream(ResourceUtils.getFile("classpath:excel-templates/"+tempName));
    }
}

到这里需要加一个excel模版

名称自己定义,根据TemplateFileUtil类的路径和名称定义。

调用:

  这是下面用到的时间转换类 
 private String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        return sdf.format(new Date());
    }

 List<自己定义的bean> list =new ArrayList<>();
list.add(..);
  Map<String, String> map = new HashMap<String, String>();
        map.put("title","");
        map.put("total", " 条");
        map.put("date", getDate());
 ExcelUtil.getInstance().exportObj2ExcelByTemplate(map,"web-info-template.xls",new FileOutputStream("导出的路径.xls"),list,自己定义的bean.class,true);

模版bean

public class Repexcel {
    private String  host;
    private Integer number;
    private String goods;


    public Repexcel(String host, Integer number, String goods) {
        this.host = host;
        this.number = number;
        this.goods = goods;
    }
    public Repexcel() {}

    @Override
    public String toString() {
        return "Repexcel{" +
                "host='" + host + '\'' +
                ", number='" + number + '\'' +
                ", goods='" + goods + '\'' +
                '}';
    }
    @ExcelResources(title="地址",order=1)
    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }
    @ExcelResources(title="柜号",order=2)
    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }
    @ExcelResources(title="商品名称",order=3)
    public String getGoods() {
        return goods;
    }

    public void setGoods(String goods) {
        this.goods = goods;
    }
}

这个工具类唯一一点,图片的导出没弄出来,不过没有图片的话上面的是非常好的选择,只需要定义一个bean就可以实现。

下面说一下导出图片和修改excel行宽和高的坑:

看来许多的博客方法很多,但是都是给一个属性,具体的没说明白,尝试了很多次才弄明白:

先说图片的导出:我的图片是上传的服务器上的,首先得到的是一个超链接需要一个工具类

public class ImgExcelUtil {
    public static void  drawPictureInfoExcel(String imgUrl,HSSFWorkbook wb, HSSFPatriarch patriarch, int rowIndex,short col) {
        try {
            URL url = new URL(imgUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5*1000);
            InputStream inputStream=httpURLConnection.getInputStream();
            byte[] data=readInputStream(inputStream);
            //anchor主要用于设置图片的属性
            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 250,col, rowIndex, col, rowIndex);
            patriarch.createPicture(anchor, wb.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


}
具体的导出excel方法
 
  public static void main(String[] args) {
        String[] title = {"大区","省份","城市","图片"};
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        HSSFCellStyle cellStyle=wb.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置水平居中
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//设置垂直居中
        cellStyle.setWrapText(true);
        CellRangeAddress rangeAddress=new CellRangeAddress(0,0,0,title.length);
        sheet.addMergedRegion(rangeAddress);
        HSSFRow row3 = sheet.createRow(0);
        HSSFCell cell3=row3.createCell(0);
        cell3.setCellValue("测试");
        cell3.setCellStyle(cellStyle);
        row3.setHeight((short) (30*20));
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        HSSFRow row = sheet.createRow(1);
        HSSFCell cell = null;
        //插入第一行数据 id,name,sex
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(cellStyle);
            sheet.setColumnWidth(i,30*256);//设置宽度
            row.setHeight((short) (30*20));//设置高度
        }
        for(int i = 1;i<5;i++){
            HSSFRow nextrow = sheet.createRow(i+1);
            nextrow.setHeight((short) (20*50));
            HSSFCell cell2 = nextrow.createCell(0);
            cell2.setCellValue(i);
            cell2.setCellStyle(cellStyle);//设置的宽度和高度一定要带入
            cell2=nextrow.createCell(1);
            cell2.setCellValue(i);
            cell2.setCellStyle(cellStyle);
            cell2=nextrow.createCell(2);
            cell2.setCellValue(i);
            cell2.setCellStyle(cellStyle);
            ImgExcelUtil.drawPictureInfoExcel("http://coolgrid.oss-cn-shanghai.aliyuncs.com/addPoint/aaa42101-db6e-4db1-ad5a-5164c65febe7.jpg",wb,patriarch,i+1, (short) 3);
            File file = new File("d:/text.xls");
            try {
                file.createNewFile();
                //将Excel内容存盘
                FileOutputStream stream = FileUtils.openOutputStream(file);
                wb.write(stream);
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




 

title我没做,可以自己写一下。。 以上就是我的踏坑,在设置宽高的时候

sheet.setDefaultColumnWidth();

sheet.setDefaultRowHeight();

这个两个属性不适用,总是设置不了,最后用了

sheet.setColumnWidth(i,30*256);//设置宽度
row.setHeight((short) (30*20));
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慕孑晨

请大家多多支持,后续不断更新

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值