jxl 读取xls,并转为二维数组可进行保存

jxl.jar: 

通过java操作excel表格的工具类库
支持Excel 95-2000的所有版本
生成Excel 2000标准格式
支持 字体、数字、日期操作
能够修饰单元格属性
支持图像和图表
应该说以上功能已经能够大致满足我们的需要。最关键的是这套API是纯Java的,并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。另外需要说明的是,这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。

  直接上代码:jxl操作xls其实很简单

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.LabelCell;
import jxl.Sheet;
import jxl.Workbook;

public class Jxl {
    // 以下是导入excel的一系列属性
    private static Sheet sheet;
    private static String[][] excelValue;

    public static void main(String[] args) {
        File upload = new File("D://1.xls");
        if (upload.exists()) {
            initExcel(upload); // 初始化
            readExcel(); // 读取
        } else {
            System.out.println("file is not found");
        }
        System.out.println(excelValue[1][1]);// 输出验证下是否存入二维数组
    }

    /**
     * 读取excel文件中数据,保存到sheet对象中
     * 
     * @param upload
     *            可以通用
     */
    private static void initExcel(File upload) {
        Workbook rwb = null;
        try {
            InputStream is = new FileInputStream(upload);
            rwb = Workbook.getWorkbook(is);
            // 获得第一个工作表对象
            sheet = rwb.getSheet(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取excel中数据进入excelValue数组中
     * 
     * 可以通用
     */
    private static void readExcel() {
        excelValue = new String[sheet.getRows()][sheet.getColumns()]; // 将行和列存储到二维数组中
        for (int i = 0; i < sheet.getRows(); i++)
            for (int j = 0; j < sheet.getColumns(); j++) {
                Cell cell = sheet.getCell(j, i);// 将工作表分成一块一块
                if ("".equals(cell.getContents().toString().trim())) {
                    excelValue[i][j] = "";
                }
                if (cell.getType() == CellType.LABEL) {
                    LabelCell labelcell = (LabelCell) cell;
                    excelValue[i][j] = labelcell.getString().trim();
                } else if (cell.getType() == CellType.NUMBER) {
                    excelValue[i][j] = cell.getContents();
                } else if (cell.getType() == CellType.DATE) {
                    DateCell datcell = (DateCell) cell;
                    excelValue[i][j] = datcell.getDate().toString();
                } else {
                    excelValue[i][j] = cell.getContents().toString().trim();
                }
            }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值