java 读取excel文件

  我查了下资料,大概了解到二者的区别:apache的poi是跨平台的,可以读取Microsoft office 文件(world,excel等),但是功能比较复杂,可能不太容易上手。而jxl.jar 是专门针对读取excel文件的,需要下载jexcelapi_2_6_12.tar.gz ,解压出来jxl.jar.

  我使用的是jxl.jar的方式,主要参考了 http://blog.csdn.net/tkd03072010/article/details/6692366  这篇文章。

  下面看看我写的代码:

  

package com.arche.alderman.mvc.pub.controller.implement;


import com.arche.alderman.mvc.base.controller.BaseAction;

import jxl.Cell;

import jxl.Sheet;

import jxl.Workbook;

import jxl.read.biff.BiffException;


import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;


import static com.arche.alderman.constant.ActionResultString.ACTION_RESULT_JSON;

import static com.arche.alderman.constant.ResponseStatusCode.REP_SERVER_HANDLE_SUCCESS;


/**

 * Created by hexiaoyu on 2015/7/9.

 */

public class TestReadExcel extends BaseAction{


    public String readExcel(){


        try {

            String fileName = "C:/Users/dswl/Desktop/s.xlsx"; // Excel文件所在路径

            File file = new File(fileName); // 创建文件对象

            Workbook wb = Workbook.getWorkbook(file); // 从文件流中获取Excel工作区对象(WorkBook)

            Sheet sheet = wb.getSheet(0); // 从工作区中取得页(Sheet)


            List<String> list = new ArrayList();


            for (int i = 0; i < sheet.getRows(); i++) { // 循环打印Excel表中的内容

                for (int j = 0; j < sheet.getColumns(); j++) {

                    Cell cell = sheet.getCell(j, i);

                    System.out.println(cell.getContents());

                    list.add(j,cell.getContents());

                }

            }

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

            setServerResponseResult(REP_SERVER_HANDLE_SUCCESS, null, list);

        } catch (BiffException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();


        }

        return ACTION_RESULT_JSON;

    }

}

代码很简洁,我也测试过,是可以读取的,因为我是要返回到页面上,所以是放到list中,再以json的形式返回的。

有遇到值得注意的问题是:初次读取会报错--Unable to recognize OLE stream,网上说是不能读取.xlsx(office2007+),只能读取.xls(office2003),但是我发现只需要自己新建一个.xlsx文件,然后把原来文件里的内容考进来就可以读取~\(≧▽≦)/~啦啦啦!

哈哈~虽然今天老大说不用动态读取了,但又学到了一点,还是很开心!继续努力咯!




你可能感兴趣的:(java 读取excel文件)