通过
jxl.jar读写Excel:
package com.pub.util;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ExlUtil {
    public static Vector readExl(String fileName) {
        Vector vec1 = null;
        Vector vec2 = new Vector();
        File f = new File(fileName);
        try {
            // 构建Workbook对象, 只读Workbook对象
            Workbook workbook = Workbook.getWorkbook(f);
            // 获取第一张Sheet表
            Sheet sheet = workbook.getSheet(0);
            // 获取行数
            int rows = sheet.getRows();
            // 获取列数
            int columns = sheet.getColumns();
            for (int i = 0; i < rows; i++) {
                vec1 = new Vector();
                for (int j = 0; j < columns; j++) {
                    // 获取j列i行的值
                    String cbxmdm = sheet.getCell(j, i).getContents();
                    if (cbxmdm == null)
                        cbxmdm = "";
                    vec1.add(cbxmdm);
                }
                if (vec1 != null)
                    vec2.add(vec1);
            }
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return vec2;
    }
    public static void writeExl(String fileName, Vector vec) {
        WritableWorkbook book = null;
        WritableSheet sheet = null;
        try {
            book = Workbook.createWorkbook(new File(fileName));
            // 生成名为“第一页”的工作表,参数0表示这是第一页
            sheet = book.createSheet("第一页", 0);
            // 打开文件
            for (int i = 0; i < vec.size(); i++) {
                // 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
                Vector vec2 = (Vector) vec.get(i);
                for (int j = 0; j < vec2.size(); j++) {
                    // 第i行第j列
                    Label label = new Label(j, i, (String) vec2.get(j));
                    // 将定义好的单元格添加到工作表中
                    sheet.addCell(label);
                }
            }
            // 写入数据并关闭文件
            book.write();
            book.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        ExlUtil.writeExl("f:/new.xls", ExlUtil.readExl("f:/xx.xls"));
    }
}
	posted on 2008-01-21 16:37 
一凡 阅读(409) 
评论(0)  编辑  收藏  所属分类: 
JAVA 基础