Java使用jxl读Excel简单例子

Java通过jxl读Excel,唯一前提:引入jxl.jar包。 

package com.neusoft.excel;

import java.io.File;

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

/**
 * jxl读excel
 * 
 * @author jianggujin
 * 
 */
public class ReadExcel {
	public static void main(String[] args) throws Exception {

		String filepath = "D:\\data";
		File file = new File(filepath);
		if (file.isDirectory()) {
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(filepath + "\\" + filelist[i]);
				if (!readfile.isDirectory()) {
					System.out.println("第【"+(i+1)+"】个文件:" + readfile.getName());
					readExcel(readfile);
					//break;
				}
			}
			System.out.println("执行完毕");

		}

	}

	public static void readExcel(File xlsFile) throws Exception {
		// 获得工作簿对象
		Workbook workbook = Workbook.getWorkbook(xlsFile);
		// 获得所有工作表
		Sheet[] sheets = workbook.getSheets();
		// 遍历工作表
		if (sheets != null) {
			for (Sheet sheet : sheets) {
				// 获得行数
				int rows = sheet.getRows();
				// 获得列数
				int cols = sheet.getColumns();
				String name = "";
				String sex = "";
				String id = "";
				String comp = "";
				// 读取数据
				for (int row = 1; row < rows; row++) {
					for (int col = 0; col < cols; col++) {
						System.out.printf("%10s", sheet.getCell(col, row).getContents());
						if (col == 1) {
							name = sheet.getCell(col, row).getContents();
						}
						if (col == 2) {
							sex = sheet.getCell(col, row).getContents();
						}
						if (col == 4) {
							id = sheet.getCell(col, row).getContents();
						}
						if (col == 5) {
							comp = sheet.getCell(col, row).getContents();
						}

					}
					writeExcel(name, sex, id, comp);
					System.out.println();
				}
			}
		}
		workbook.close();
	}

	public static void writeExcel(String name, String sex, String id, String comp) throws Exception {
		File xlsFile = new File("demo.xls");
		Workbook book = Workbook.getWorkbook(xlsFile);
		// 创建一个工作簿
		WritableWorkbook workbook = Workbook.createWorkbook(xlsFile, book);
		// 创建一个工作表
		WritableSheet sheet = workbook.getSheet(0);
		int rows = sheet.getRows();
		System.out.println(rows);
		// for (int row = rows; row < 20; row++) {
		// for (int col = 0; col < 10; col++) {
		// 向工作表中添加数据
		sheet.addCell(new Label(1, rows, name));
		sheet.addCell(new Label(2, rows, sex));
		sheet.addCell(new Label(6, rows, id));
		sheet.addCell(new Label(12, rows, comp));
		// }
		// }
		workbook.write();
		workbook.close();
	}

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值