Smal1_Sun 2016-03-29 11:44 采纳率: 50%
浏览 1600

使用Java导出excel文档,为何数据库中int类型的导出不成功?

导出工具类

 package com.lovefly.util;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import com.lovefly.service.api.excel.Excelable;

public class ExcelUtil<T extends Excelable> {
    private WritableWorkbook book ;
    private WritableSheet sheet;
    private int rowIndex = 0;
    List<String> attrs;
    List<T> poList;
    Class<T> clas;

    public ExcelUtil(OutputStream out,String name,List<String> attrs,List<T> poList,Class<T> c) throws IOException {
        book = Workbook.createWorkbook(out);
        sheet = book.createSheet(name, 0);
        this.attrs = attrs;
        this.poList = poList;
        clas = c;
    }

    private void writeBody() throws Exception {
        Label label = null;
        for(int i=0;i<poList.size();i++){
            for(int j=0;j<attrs.size();j++){
                Field field = clas.getDeclaredField(attrs.get(j));
                field.setAccessible(true);
                label = new Label(j,rowIndex,field.get(poList.get(i)).toString());
                sheet.addCell(label);
            }
            rowIndex++;
        }
    }

    private void writeTitle() throws Exception{
        Label label = null;
        for(int i=0;i<attrs.size();i++){
            label = new Label(i,rowIndex,clas.newInstance().getAttrTitleMapping().get(attrs.get(i)));
            sheet.addCell(label);
        }
        rowIndex++;
    }

    public void writeClose(){
        try {
            writeTitle();
            writeBody();
            book.write();
            book.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 写回答

1条回答 默认 最新

  • IT_xiao菜鸟 2016-03-30 09:23
    关注

    这个工具类,跟你是什么类型是没关系的
    for(int j=0;j<attrs.size();j++){
    Field field = clas.getDeclaredField(attrs.get(j));
    field.setAccessible(true);
    label = new Label(j,rowIndex,field.get(poList.get(i)).toString());
    sheet.addCell(label);
    }
    Field field = clas.getDeclaredField(attrs.get(j)); 根据你传入的名称获得这个class的成员变量
    比如我们传入了student 类 有id,age,name 三个属性

    你的attrs 集合里面应该存入了attrs[0]="id",attrs[1]="age",attrs[2]="name"
    假如j=0:现在的field=student.id;获取到了student.id成员变量;
    field.get(poList.get(i))---获取class的成员变量的值
    你传入的是student 类的集合,所以你可以获取到第一个student 的id的值
    如果是int类型的值你做.tostring(),肯定不行的啊,int 是没有tostring()方法的

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算