将excel文件导出不作任何操作再导入,用poi解析不到数据

[size=large][size=medium][/size]现在系统有一个解析excel的功能,将导入excel文件解析然后保存入库,可以将导入的文件导出查看,导出类型也是xls;

问题是导入一个有数据的excel文件, 导入成功后,再导出,对导出的excel文件不做任何处理再倒入,java poi 解析不到数据; 如果将导出的excel文件打开随便点一下,保存再倒入,就可以解析了;我觉得可能是excel中没有焦点的情况下,poi解析不到数据。

还请各位指点啊...[/size]

[quote]我觉得还是要考虑这个焦点,只要excel中有焦点,就可以解析了 [/quote]
你要这么考虑 方向就偏了,两个应用程序,你怎么可能去得到excel的焦点了。
只能说你得到excel焦点后就可以成功这件事儿应该说明别的问题。
你这个在生成之后应该是有个跳转吧,你把response.reset();这句话加在下载的代码前试试。

你每次操作了,都把流关闭了,然后再执行下一步操作。

那可能是导出的时候,虽然方法执行了,但是文件还木有生成完,就重新去读取了,没有等待的过程。

把你导出excel后的关闭代码贴一下

package com.byd.core;

import java.io.File;package com.byd.core;

import java.io.OutputStream;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Date;

import java.util.Iterator;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelExport {

//格式化日期

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

/**

*

* @param title 标题

* @param dataset 集合

* @param out 输出流

*/

@SuppressWarnings("unchecked")

public void exportExcel(String title, Collection dataset,

OutputStream out) {

// 声明一个工作薄

try {

//首先检查数据看是否是正确的

Iterator its = dataset.iterator();

System.out.println(dataset.size());

if(dataset==null||!its.hasNext()||title==null||out==null)

{

throw new Exception("传入的数据不对!");

}

//取得实际泛型类

int index = 0;

HSSFWorkbook workbook = new HSSFWorkbook();

// 生成一个表格

HSSFSheet sheet = workbook.createSheet(title);

List methodObj = new ArrayList();

while (its.hasNext()) {

index++;

T ts = (T) its.next();

if (index==1){

Class tCls = ts.getClass();

//HSSFWorkbook workbook = new HSSFWorkbook();

// 生成一个表格

//HSSFSheet sheet = workbook.createSheet(title);

// 设置表格默认列宽度为15个字节

sheet.setDefaultColumnWidth(15);

// 生成一个样式

HSSFCellStyle style = workbook.createCellStyle();

// 设置标题样式

style = ExcelStyle.setHeadStyle(workbook, style);

// 得到所有字段

Field filed[] = ts.getClass().getDeclaredFields();

// 标题

List exportfieldtile = new ArrayList();

// 导出的字段的get方法

//List methodObj = new ArrayList();

// 遍历整个filed

for (int i = 0; i < filed.length; i++) {

Field f = filed[i];

ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);

// 如果设置了annottion

if (exa != null) {

String exprot = exa.exportName();

// 添加到标题

exportfieldtile.add(exprot);

// 添加到需要导出的字段的方法

String fieldname = f.getName();

String getMethodName = "get"

+ fieldname.substring(0, 1).toUpperCase()

+ fieldname.substring(1);

                        Method getMethod = tCls.getMethod(getMethodName,      
                                new Class[] {});      


                        methodObj.add(getMethod);      
                    }      
                }      
                // 产生表格标题行      
                HSSFRow row = sheet.createRow(0);      
                for (int i = 0; i < exportfieldtile.size(); i++) {      
                    HSSFCell cell = row.createCell(i);      
                    cell.setCellStyle(style);      
                    HSSFRichTextString text = new HSSFRichTextString(      
                            exportfieldtile.get(i));      
                    cell.setCellValue(text);     
                    System.out.println(text);   
                }      
           }   


            // 循环整个集合      

            //while (its.hasNext()) {      
                //从第二行开始写,第一行是标题      
               // index++;      
              HSSFRow row = sheet.createRow(index);      
                //T t = (T) its.next();      
                for (int k = 0; k < methodObj.size(); k++) {      
                    HSSFCell cell = row.createCell(k);      
                    Method getMethod=methodObj.get(k);      
                    Object value = getMethod.invoke(ts, new Object[] {});      
                    String textValue = getValue(value);    
                    cell.setCellValue(textValue);     
                }    
            }      
            workbook.write(out);     
       // }      
    } catch (Exception e) {      
        e.printStackTrace();      
    }      

}      

public String getValue(Object value) {      
    String textValue = "";      
    if (value == null)      
        return textValue;      

    if (value instanceof Boolean) {      
        boolean bValue = (Boolean) value;      
        textValue = "是";      
        if (!bValue) {      
            textValue = "否";      
        }      
    } else if (value instanceof Date) {      
        Date date = (Date) value;      

        textValue = sdf.format(date);      
    }else textValue=value.toString();   

    return textValue;      
}      

/*public static void main(String[] args) throws Exception {     

    //构造一个模拟的List来测试,实际使用时,这个集合用从数据库中查出来     
    List list = new ArrayList();     
    for (int i = 0; i < 5000; i++) {     
        Testpojo pojo = new Testpojo();     
        pojo.setLoginname("登录名"+i);     
        pojo.setUsername("用户名"+i);     
        pojo.setMoney(new Long(1000+i));     
        pojo.setCreatetime(new Date());     
        pojo.setAge(28);     
        list.add(pojo);     
    }     
    //构造输出对象,可以从response输出,直接向用户提供下载     
    OutputStream out = new FileOutputStream("D:\\testOne.xls");     
    //开始时间     
    Long l = System.currentTimeMillis();     
    //注意     
    ExcelExport<Testpojo> ex = new ExcelExport<Testpojo>();     
    //     
    ex.exportExcel("测试", list, out);     
    out.close();     
    //结束时间     
    Long s = System.currentTimeMillis();     
    System.out.println("总共耗时:" + (s - l));     

}   */  

}

import java.io.FileInputStream;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.lang.reflect.Type;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Date;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

public class ImportExcel {

Class clazz;

    public ImportExcel(Class<T> clazz) {   
        this.clazz = clazz;   
    }   

    @SuppressWarnings("unchecked")   
    public Collection<T> importExcel(File file ,String...  pattern) {   
        Collection<T> dist = new ArrayList();   
        try {   
            /**  
             * 类反射得到调用方法  
             */  
            // 得到目标目标类的所有的字段列表   
            Field filed[] = clazz.getDeclaredFields();   
            // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中   
            Map fieldmap = new HashMap();   
            // 循环读取所有字段   
            for (int i = 0; i < filed.length; i++) {   
                Field f = filed[i];   
                // 得到单个字段上的Annotation   
                ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);   
                // 如果标识了Annotationd的话   
                if (exa != null) {   
                    // 构造设置了Annotation的字段的Setter方法   
                    String fieldname = f.getName();   
                    String setMethodName = "set"  
                            + fieldname.substring(0, 1).toUpperCase()   
                            + fieldname.substring(1);   
                    // 构造调用的method,   
                    Method setMethod = clazz.getMethod(setMethodName,   
                            new Class[] { f.getType() });   
                    // 将这个method以Annotaion的名字为key来存入。   
                    fieldmap.put(exa.exportName(), setMethod);   
                }   
            }   
            /**  
             * excel的解析开始  
             */  
            // 将传入的File构造为FileInputStream;   
            FileInputStream in = new FileInputStream(file);   
            // // 得到工作表   
            HSSFWorkbook book = new HSSFWorkbook(in);   
            // // 得到第一页   
            HSSFSheet sheet = book.getSheetAt(0);   
            // // 得到第一面的所有行   
            Iterator<Row> row = sheet.rowIterator();   

            /**  
             * 标题解析  
             */  
            // 得到第一行,也就是标题行   
            Row title = row.next();   
            // 得到第一行的所有列   
            Iterator<Cell> cellTitle = title.cellIterator();   
            // 将标题的文字内容放入到一个map中。   
            Map titlemap = new HashMap();   
            // 从标题第一列开始   
            int i = 0;   
            // 循环标题所有的列   
            while (cellTitle.hasNext()) {   
                Cell cell = cellTitle.next();   
                String value = cell.getStringCellValue();   
                titlemap.put(i, value);   
                i = i + 1;   
            }   
            /**  
             * 解析内容行  
             */  
            //用来格式化日期的DateFormat   
            SimpleDateFormat sf;   
            if(pattern.length<1)   
            {   
                sf=new SimpleDateFormat("yyyy-MM-dd");     
            }   
            else  
                sf=new SimpleDateFormat(pattern[0]);       
            while (row.hasNext()) {   
                // 标题下的第一行   
                Row rown = row.next();   

                // 行的所有列   
                Iterator<Cell> cellbody = rown.cellIterator();   
                // 得到传入类的实例   
                T tObject = clazz.newInstance();   
                int k = 0;   
                // 遍历一行的列   
                while (cellbody.hasNext()) {   
                    Cell cell = cellbody.next();   
                    // 这里得到此列的对应的标题   
                    String titleString = (String) titlemap.get(k);   
                    // 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值   
                    if (fieldmap.containsKey(titleString)) {   
                        Method setMethod = (Method) fieldmap.get(titleString);   
                        //得到setter方法的参数   
                        Type[] ts = setMethod.getGenericParameterTypes();   
                        //只要一个参数   
                        String xclass = ts[0].toString();   
                        //判断参数类型   


                        if(xclass.equals("class java.lang.String"))   
                        {   
                            setMethod.invoke(tObject, cell.getStringCellValue());   
                        }   
                        else if(xclass.equals("class java.util.Date"))   
                        {   
                            setMethod.invoke(tObject, sf.parse(cell.getStringCellValue()));   
                        }   
                        else if(xclass.equals("class java.lang.Boolean"))   
                        {   
                            Boolean boolname=true;   
                            if(cell.getStringCellValue().equals("否"))   
                                {   
                                boolname=false;   
                                }   
                            setMethod.invoke(tObject,boolname );   
                        }   
                        else if(xclass.equals("class java.lang.Integer"))   
                        {   
                            setMethod.invoke(tObject,new Integer( cell.getStringCellValue()));   
                        }   

                        else if(xclass.equals("class java.lang.Long"))   
                        {   
                            setMethod.invoke(tObject,new Long( cell.getStringCellValue()));   
                        }   
                    }   
                    // 下一列   
                    k = k + 1;   
                }   
                dist.add(tObject);   
            }   
        } catch (Exception e) {   
            e.printStackTrace();   
            return null;   
        }   
        return dist;   
    }   

public String exportDate(String fileName,String rootPath,Collection dataset,OutputStream out) throws UnsupportedEncodingException{

String xlsPath = rootPath + "main\download\"+fileName+".xls";

String path="download/"+fileName+".xls";

String down =new String(path.getBytes(),"utf-8");

File file = new File(xlsPath + "\main\download\");

if (file.listFiles() != null) {

for (int i = 0; i < file.listFiles().length; i++) {

if (file.listFiles()[i].getName().endsWith(".xls")){

boolean flag=file.listFiles()[i].delete();

if(flag){

try {

out = new FileOutputStream(rootPath

+ "\main\download\" + fileName + ".xls");

this.exportExcel(fileName, dataset, out);

out.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

}

return down;

}

/*public static void main(String[] args) {

ImportExcel test = new ImportExcel(Testpojo.class);

File file = new File("D:\order.xls");

Long befor = System.currentTimeMillis();

List result = (ArrayList) test.importExcel(file);

        Long after = System.currentTimeMillis();  
        System.out.println("此次操作共耗时:" + (after - befor) + "毫秒");  
         for (int i = 0; i < result.size(); i++) {  
             Testpojo testpojo=result.get(i);  
         System.out.println("导入的信息为:"+testpojo.getLoginname()+  
                 "----"+testpojo.getAge()+"---"+testpojo.getMoney()+"-----"+testpojo.getCreatetime());  
         }  

        System.out.println("共转化为List的行数为:" + result.size());  
    }*/  

}

按我这个可以导出一个空Excel模板 模板填数据再倒入数据 基本没什么问题

楼主问题解决了吗?遇到同样的问题,流关闭也不管用

实现excel文件 的导入导出 ,楼主可以用pageoffice插件的