JXL读写Excel

2021-12-08 08:41:01 浏览数 (1)

使用JXL生成Excel文

代码语言:javascript复制
package test.jxl;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.commons.lang3.RandomStringUtils;

import java.io.File;
import java.io.IOException;

/**
 * 功能:
 * 作者: yangyan
 * 时间: 2015/4/13 .
 */
public class JxlExpExcel {
    public static void main(String[] args) throws WriteException {

//        表头
        String headers[] = new String[]{"user", "gender", "age"};

//        创建excel文件
        File file = new File("test_file/jxl_test.xls");

        try {
            file.getParentFile().mkdirs();
            file.createNewFile();
//            创建工作簿
            WritableWorkbook writableWorkbook = Workbook.createWorkbook(file);
            WritableSheet sheet1 = writableWorkbook.createSheet("sheet1", 0);
//            设置表头
            for (int i = 0; i < headers.length; i  ) {
                Label label = new Label(i, 0, headers[i]);
                sheet1.addCell(label);
            }

//            追加数据
            for (int i = 1; i < 10; i  ) {
                Label label = new Label(0, i, "a"   1);
                sheet1.addCell(label);
                Label label2 = new Label(1, i, "男");
                sheet1.addCell(label2);
                Label label3 = new Label(2, i, RandomStringUtils.randomNumeric(2));
                sheet1.addCell(label3);
            }

            writableWorkbook.write();
            writableWorkbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用JXL读取Excel文件

代码语言:javascript复制
package test.jxl;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import java.io.File;
import java.io.IOException;

/**
 * 功能:
 * 作者: yangyan
 * 时间: 2015/4/13 .
 */
public class JxlReadExcel {
    public static void main(String[] args) {
        try {
            Workbook workbook = Workbook.getWorkbook(new File("test_file/jxl_test.xls"));
            Sheet sheet1 = workbook.getSheet("sheet1");

            for (int i = 0; i < sheet1.getRows(); i  ) {
                for (int j = 0; j < sheet1.getColumns(); j  ) {
                    Cell cell = sheet1.getCell(j, i);
                    System.out.print(cell.getContents()   "t");
                }
                System.out.println("n");
            }
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
    }
}

maven配置如下:

代码语言:javascript复制
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>

0 人点赞